我有一个数组:

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

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

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


当前回答

Undercore.js有一个很好的方法:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })

其他回答

使用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;
    });
}

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

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

array.find( {id: 75} );

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

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

由于您已经在使用jQuery,因此可以使用grep函数来搜索数组:

var result = $.grep(myArray, function(e){ return e.id == id; });

结果是找到项的数组。如果您知道对象始终存在,并且它只出现一次,那么只需使用result[0].foo获取值。否则,应检查结果数组的长度。例子:

if (result.length === 0) {
  // no result found
} else if (result.length === 1) {
  // property found, access the foo property using result[0].foo
} else {
  // multiple items found
}

尝试以下操作

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

考虑“axesOptions”是对象数组,对象格式为{:字段类型=>2,:字段=>[1,3,4]}

function getFieldOptions(axesOptions,choice){
  var fields=[]
  axesOptions.each(function(item){
    if(item.field_type == choice)
        fields= hashToArray(item.fields)
  });
  return fields;
}