Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 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 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...