通过ID在JavaScript对象数组中查找对象

本文翻译自:Find object by id in an array of JavaScript objects

I've got an array: 我有一个数组:

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

I'm unable to change the structure of the array. 我无法更改数组的结构。 I'm being passed an id of 45 , and I want to get 'bar' for that object in the array. 我正在传递id为45 ,并且我想为数组中的该对象获取'bar'

How do I do this in JavaScript or using jQuery? 如何在JavaScript或jQuery中做到这一点?


#1楼

参考:https://stackoom.com/question/Utkc/通过ID在JavaScript对象数组中查找对象


#2楼

A generic and more flexible version of the findById function above: 上面的findById函数的通用且更灵活的版本:

// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');

#3楼

You may try out Sugarjs from http://sugarjs.com/ . 您可以从http://sugarjs.com/试用Sugarjs。

It has a very sweet method on Arrays, .find . 它在数组.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". 您还可以将具有更多属性的对象传递给它,以添加另一个“ where-clause”。

Note that Sugarjs extends native objects, and some people consider this very evil... 请注意,Sugarjs扩展了本机对象,有些人认为这非常邪恶。


#4楼

Underscore.js has a nice method for that: Underscore.js有一个不错的方法:

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

#5楼

Use: 采用:

var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {

        if (obj.id === '5') { // id.toString() if it is int

            retObj = obj;
            return false;
        }
    });
return retObj;

It should return an object by id. 它应该通过id返回一个对象。


#6楼

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);
发布了0 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/105222709
今日推荐