Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

javascript - 通过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中做到这一点?)

  ask by thugsb translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(由于您已经在使用jQuery,因此可以使用旨在搜索数组的grep函数:)

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

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.

(如果您知道对象始终存在并且只发生一次,则可以使用result[0].foo来获取值。)

Otherwise you should check the length of the resulting array.

(否则,您应该检查结果数组的长度。)

Example:

(例:)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...