我有一个数组:

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

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

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


当前回答

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

其他回答

由于您已经在使用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
}

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

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

下面的代码将帮助您从数据中的嵌套对象中搜索值。

const updatedData = myArrayOfObjects.filter((obj: any) => Object.values(obj).some((val: any) => {
   if (typeof (val) == typeof ("str")) {
      return val.toString().includes(Search)
   } else {
      return Object.values(val).some((newval: any) => {
         if (newval !== null) {
            return newval.toString().includes(Search)
         }
      })
   }
}))

使用find()方法:

myArray.find(x => x.id === '45').foo;

来自MDN:

如果数组中的元素满足所提供的测试函数,find()方法将返回数组中的第一个值。否则返回undefined。


如果要查找其索引,请使用findIndex():

myArray.findIndex(x => x.id === '45');

来自MDN:

findIndex()方法返回数组中满足所提供测试函数的第一个元素的索引。否则返回-1。


如果要获取匹配元素的数组,请改用filter()方法:

myArray.filter(x => x.id === '45');

这将返回一个对象数组。如果要获取foo财产数组,可以使用map()方法:

myArray.filter(x => x.id === '45').map(x => x.foo);

附带说明:旧浏览器(如IE)不支持find()或filter()和arrow函数等方法,因此如果您想支持这些浏览器,应该使用Babel(带有polyfill)来转换代码。

基于公认的答案:

jQuery:

var foo = $.grep(myArray, function(e){ return e.id === foo_id})
myArray.pop(foo)

或CoffeeScript:

foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo