查找ID对象在JavaScript中对象的数组 [英] Find object by id in an array of JavaScript objects

查看:135
本文介绍了查找ID对象在JavaScript中对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

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

我无法改变阵列的结构。我被传递 45 的ID,我想获得'酒吧'数组中的对象。

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.

我如何做到这一点的JavaScript或使用jQuery?

How do I do this in JavaScript or using jQuery?

推荐答案

当你已经在使用jQuery,您可以使用的grep其目的是用于搜索的阵列的功能:

As you are already using jQuery, you can use the grep function which is intended for searching an array:

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

结果与找到的项目阵列。如果你知道对象是永远存在的,它只能出现一次,你可以使用结果[0]包含.foo 来获得的价值。否则,你应该检查所生成的数组的长度。例如:

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

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

这篇关于查找ID对象在JavaScript中对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆