从嵌套对象获取值

时间:2013-04-30 10:38:34

标签: javascript underscore.js lodash

我正在尝试获取对象的第一个值,如:

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

这是大约100个左右的1个对象。我试图从100个对象中的每个对象中获取amount属性的第一个值list?即如此高于100

我该怎么做?我使用下划线JS?

2 个答案:

答案 0 :(得分:0)

您将列表定义为object。对象属性按其定义的顺序排列,但我们不能信任它的顺序。我认为有关于它的Chrome错误https://code.google.com/p/v8/issues/detail?id=164

以下first方法给出了list对象的第一个元素,这个函数适用于大多数情况,如果object为空,它将返回undefined值。

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;

如果您想保持列表顺序,请将它们定义为Array。例子

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]
};

并以data.list[0]

的形式访问它们

答案 1 :(得分:0)

你可以试试这个

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

如果你需要获得所有密钥,可以试试这个

 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);