在JavaScript对象数组中按ID查找对象

我有一个数组:

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

我无法更改数组的结构。我正在传递ID为45,我想获取'bar'数组中的该对象。

如何在JavaScript或jQuery中做到这一点?

路易EvaSam2020/03/09 20:52:02

This solution may helpful as well:

Array.prototype.grep = function (key, value) {
    var that = this, ret = [];
    this.forEach(function (elem, index) {
        if (elem[key] === value) {
            ret.push(that[index]);
        }
    });
    return ret.length < 2 ? ret[0] : ret;
};
var bar = myArray.grep("id","45");

I made it just like $.grep and if one object is find out, function will return the object, rather than an array.

Mandy逆天路易2020/03/09 20:52:02

Shortest,

var theAnswerObj = _.findWhere(array, {id : 42});
达蒙西里2020/03/09 20:52:02

Consider "axesOptions" to be array of objects with an object format being {:field_type => 2, :fields => [1,3,4]}

function getFieldOptions(axesOptions,choice){
  var fields=[]
  axesOptions.each(function(item){
    if(item.field_type == choice)
        fields= hashToArray(item.fields)
  });
  return fields;
}
路易Stafan2020/03/09 20:52:02

We can use Jquery methods $.each()/$.grep()

var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}

or

var data = $.grep(array, function( n, i ) {
  return ( n !== 5 && i > 4 );
});

use ES6 syntax:

Array.find, Array.filter, Array.forEach, Array.map

Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter

猿前端前端2020/03/09 20:52:02

I really liked the answer provided by Aaron Digulla but needed to keep my array of objects so I could iterate through it later. So I modified it to

	var indexer = {};
	for (var i = 0; i < array.length; i++) {
	    indexer[array[i].id] = parseInt(i);
	}
	
	//Then you can access object properties in your array using 
	array[indexer[id]].property

阿飞十三2020/03/09 20:52:02

Use Array.prototype.filter() function.

DEMO: 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
  }
 }
];

FILTER

var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return obj.name === name;
    });
}
Stafan阳光2020/03/09 20:52:02

You can do this even in pure JavaScript by using the in built "filter" function for arrays:

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

So now simply pass "id" in place of key and "45" in place of value, and you will get the full object matching an id of 45. So that would be,

myArr.filterObjects("id", "45");
SamEva2020/03/09 20:52:02

As long as the browser supports ECMA-262, 5th edition (December 2009), this should work, almost one-liner:

var bFound = myArray.some(function (obj) {
    return obj.id === 45;
});
番长前端2020/03/09 20:52:02

Building on the accepted answer:

jQuery:

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

Or CoffeeScript:

foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo
LEY西门2020/03/09 20:52:02

If you do this multiple times, you may set up a Map (ES6):

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

Then you can simply do:

map.get(27).foo
NearItachi2020/03/09 20:52:02

You may try out Sugarjs from http://sugarjs.com/.

It has a very sweet method on Arrays, .find. So you can find an element like this:

array.find( {id: 75} );

You may also pass an object with more properties to it to add another "where-clause".

Note that Sugarjs extends native objects, and some people consider this very evil...

逆天西门2020/03/09 20:52:02

You can use filters,

  function getById(id, myArray) {
    return myArray.filter(function(obj) {
      if(obj.id == id) {
        return obj 
      }
    })[0]
  }

get_my_obj = getById(73, myArray);
用户70493023002020/03/09 20:52:02
myArray.filter(function(a){ return a.id == some_id_you_want })[0]
JinJinGreen伽罗2020/03/09 20:52:02

ECMAScript 2015在数组上提供了find()方法:

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {id:3, name:"barb"},
]

// grab the Array item which matchs the id "2"
var item = myArray.find(item => item.id === 2);

// print
console.log(item.name);

它无需外部库即可工作。但是,如果您希望使用较旧的浏览器支持,则可能需要包含此polyfill

猪猪阳光2020/03/09 20:52:02

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