通过属性值从对象数组中获取 JavaScript 对象 [英] Get JavaScript object from array of objects by value of property

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

问题描述

假设我有一个包含四个对象的数组:

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}
];

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

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?

推荐答案

Filter 对象数组,属性匹配值,返回数组:

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

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

请参阅 关于 Array.prototype 的 MDN 文档.filter()

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)

查找数组中第一个元素/对象的值,否则返回undefined.

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

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

请参阅 关于 Array.prototype 的 MDN 文档.find()

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)

这篇关于通过属性值从对象数组中获取 JavaScript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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