Question

I am trying to get the first value for an object like:

{
 "_id":"123",
    "list":{"56":{"name":"Great ","amount":100,"place":"Town"},"57":{"name":"Great  2","amount":200,"place":"City"}},
    "pop":[2,3]
}

This is 1 object of around 100 or so. I am trying to get the amount from the first value of list property in each of the 100 objects ? i.e. so above it would be 100

How would I do that ? I am using underscore JS ?

Was it helpful?

Solution

You are defining list as object . Object properties are in order of they defined, but we cannot trust its order . I think there is Chrome bug about it https://code.google.com/p/v8/issues/detail?id=164

the following first method gives first element from list object , this function will works most cases , if object is empty it will return undefined value.

var data = {
 "_id":"123",
    "list":{
        "56":{"name":"Great ","amount":100,"place":"Town"},
        "57":{"name":"Great  2","amount":200,"place":"City"}
    },
    "pop":[2,3]
};


function first( data ){

    for ( var i in data ){
        if ( data.hasOwnProperty(i) ) break;    
    }

    return data.hasOwnProperty(i) ? data[i] : undefined;
}

first( data.list ).amount;

If you want to keep order of list .. define them as Array . example

var data = {
 "_id":"123",
    "list":[
        {"id" : "56" ,"name":"Great ","amount":100,"place":"Town"},
        {"id" : "57" ,"name":"Great  2","amount":200,"place":"City"}
    ],
    "pop":[2,3]
};

and access them as data.list[0]

OTHER TIPS

You can try this

function getFirstAmount(obj){
   for(var key in obj){
      return obj[key].amount;
   }
}

If you need to get all keys, you can try this

 function getAmounts(obj){
    var amounts = [];
    var  i = 0;
    for(var key in obj){
          amounts[i] = obj[key].amount;
          i++;
       }
    }
    return amounts;
 }

 //call function
   var firstAmount = getFirstAmount(obj.list);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top