0

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

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

这是大约 100 个左右的 1 个对象。我正在尝试amount从 100 个对象中的每个对象的第一个属性值中获取list?即高于它会是100

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

4

2 回答 2

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);
于 2013-04-30T12:45:42.183 回答
0

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

以下first方法给出列表对象的第一个元素,此函数在大多数情况下都有效,如果对象为空,它将返回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]

于 2013-04-30T11:11:01.503 回答