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
532 views
in Technique[技术] by (71.8m points)

javascript - 通过属性值从对象数组中获取JavaScript对象[重复](Get JavaScript object from array of objects by value of property [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

Let's say I have an array of four objects:

(假设我有四个对象组成的数组:)

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

Is there a way that I can get the third object ( {a: 5, b: 6} ) by the value of the property b for example without a for...in loop?

(有没有一种方法可以通过属性b的值获取第三个对象( {a: 5, b: 6} ),例如,没有for...in循环?)

  ask by user765368 translate from so

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

1 Reply

0 votes
by (71.8m points)

Filter array of objects, which property matches value, returns array:

(Filter对象数组,其属性与值匹配,返回数组:)

var result = jsObjects.filter(obj => {
  return obj.b === 6
})

See the MDN Docs on Array.prototype.filter()

(请参阅Array.prototype.filter()上MDN文档)

 const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.filter(obj => { return obj.b === 6 }) console.log(result) 

Find the value of the first element/object in the array, otherwise undefined is returned.

(Find数组中第一个元素/对象的值,否则返回undefined 。)

var result = jsObjects.find(obj => {
  return obj.b === 6
})

See the MDN Docs on Array.prototype.find()

(请参阅Array.prototype.find()上MDN文档)

 const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.find(obj => { return obj.b === 6 }) console.log(result) 


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

...