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

这篇文章探讨如何在JavaScript或jQuery中通过ID在对象数组中查找特定对象。提供了多种方法,包括使用Sugarjs的where方法、Underscore.js的find方法以及使用JavaScript的filter方法来实现这一目标。
摘要由CSDN通过智能技术生成

本文翻译自: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);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值