我有一个数组:

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

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

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


当前回答

以下是我将如何在纯JavaScript中实现它,以我所能想到的在ECMAScript 3或更高版本中工作的最简单的方式。一旦找到匹配项,它就会返回。

var getKeyValueById = function(array, key, id) {
    var testArray = array.slice(), test;
    while(test = testArray.pop()) {
        if (test.id === id) {
            return test[key];
        }
    }
    // return undefined if no matching id is found in array
    return;
}

var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');

// result is 'bar', obtained from object with id of '45'

其他回答

您可以使用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/

即使在纯JavaScript中,也可以通过对数组使用内置的“filter”函数来实现这一点:

Array.prototype.filterObjects = function(key, value) {
    return this.filter(function(x) { return x[key] === value; })
}

所以现在只需用“id”代替key,用“45”代替value,就会得到与id 45匹配的完整对象。那就是,

myArr.filterObjects("id", "45");

如果多次执行此操作,则可以设置映射(ES6):

const map = new Map( myArray.map(el => [el.id, el]) );

然后,您可以简单地执行O(1)查找:

map.get(27).foo

使用Array.prototype.filter()函数。

演示:https://jsfiddle.net/sumitridhal/r0cz0w5o/4/

JSON

var jsonObj =[
 {
  "name": "Me",
  "info": {
   "age": "15",
   "favColor": "Green",
   "pets": true
  }
 },
 {
  "name": "Alex",
  "info": {
   "age": "16",
   "favColor": "orange",
   "pets": false
  }
 },
{
  "name": "Kyle",
  "info": {
   "age": "15",
   "favColor": "Blue",
   "pets": false
  }
 }
];

过滤器

var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return obj.name === name;
    });
}

我认为最简单的方法是以下方法,但它在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