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

查看:183
本文介绍了通过property的值从对象数组中获取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}
];

有没有办法可以获得第三个对象( {a: 5,b:6} )通过属性 b 的值,例如没有 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 array of objects, which property matches value, returns array:

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

参见 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)

查找数组中第一个元素/对象的值,否则返回 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.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)

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

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