我有一个数组:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]

我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。

如何在JavaScript或使用jQuery实现这一点?


当前回答

尝试以下操作

function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
    }
  }
  throw "Couldn't find object with id: " + id;
}

其他回答

ECMAScript 2015(JavaScript ES6)提供find()数组上的方法:

var myArray=[{id:1,name:“bob”},{id:2,名称:“dan”},{id:3,名称:“barb”},]//抓取与id“2”匹配的Array项var item=myArray.find(item=>item.id===2);//打印console.log(item.name);

它在没有外部库的情况下工作。但是,如果您想要更旧的浏览器支持,您可能需要包含此polyfill。

你可以试试Sugarjshttp://sugarjs.com/.

它在Arrays上有一个非常好的方法,.find。所以你可以找到这样的元素:

array.find( {id: 75} );

您还可以向其传递具有更多财产的对象,以添加另一个“where-clause”。

请注意,Sugarjs扩展了本地对象,有些人认为这非常邪恶。。。

尝试以下操作

function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
    }
  }
  throw "Couldn't find object with id: " + id;
}

我认为最简单的方法是以下方法,但它在Internet Explorer 8(或更早版本)上不起作用:

var result = myArray.filter(function(v) {
    return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property

您可以使用map()函数轻松实现这一点:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var found = $.map(myArray, function(val) {
    return val.id == 45 ? val.foo : null;
});

//found[0] == "bar";

工作示例:http://jsfiddle.net/hunter/Pxaua/