如何从对象数组中获取元素?

时间:2013-10-29 11:46:39

标签: javascript underscore.js

var fkTableArr1d = new Array();

fkTableArr1d = _.map(fkTableArr2d, function(list, iterator, context) {          
      return { "id " : list[0], "label " : list[1] };
    });

fkTableArr1d变为: [Object, Object, Object]

1个对象是Object {id : "5", label : "fuel"}

现在我应该如何获得标签为fuel的元素的ID?

下面一个不起作用:

console.log(fkTableArr1d['fuel']);

3 个答案:

答案 0 :(得分:2)

看起来您正在寻找findWhere()

  

查看列表并返回与所有匹配的第一个值   属性中列出的键值对。

_.findWhere(fkTableArr1d, {label : "fuel"});

演示:http://jsfiddle.net/38qUE/1/

答案 1 :(得分:0)

var id = 0;
if(fkTableArr1d.label = 'fuel') id = fkTableArr1d.id;

Fiddle

答案 2 :(得分:0)

使用以下任何代码段:

snippet1:

fkTableArr1d =[{id : "5", label : "fuel1"}, {id : "6", label : "fuel"}, {id : "4", label : "fuel2"}];
for(x in fkTableArr1d)
    if(fkTableArr1d[x].label == 'fuel')
        alert(fkTableArr1d[x]['id']);//syntax1 for accessing object member. alerts '6'.

<强> fiddle1

snippet2:

fkTableArr1d =[{id : "5", label : "fuel1"}, {id : "6", label : "fuel"}, {id : "4", label : "fuel2"}];
for(x in fkTableArr1d)
    if(fkTableArr1d[x].label == 'fuel')
        alert(fkTableArr1d[x].id);//syntax2 for accessing object member. alerts '6'.

<强> fiddle2