根据值从对象数组中选择一个属性:Javascript [英] Select a property from an array of objects based on a value : Javascript

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

问题描述

我有一个具有以下结构的对象数组:

I have an array of objects with the following structure:

var arr = [
  {
    "value": "abc",
    "checked": true
  },
  {
    "value": "xyz",
    "checked": false
  },
  {
    "value": "lmn",
    "checked": true
  }
];

let result = arr.filter(item => item.checked);

console.log(result);

我希望输出为:

["abc", "lmn"] 

因为这两个value具有checked: true.

我尝试根据检查的值进行过滤:

I have tried filtering out based on checked value:

let result = arr.filter(item => item.checked);

我正在获取具有checked属性值并设置为true的对象.

I am getting the objects that has checked property value that is set to true.

我们将不胜感激.

推荐答案

您可以使用reduce并检查checked属性是否为true,然后检查push(如

You can use reduce and check if the checked property is true, then push (As pointed out by assoron) the value to the accumulator - there is no need for 2 loops:

const arr = [
  { "value": "abc", "checked": true },
  { "value": "xyz", "checked": false },
  { "value": "lmn", "checked": true }
]

const filtered = arr.reduce((a, o) => (o.checked && a.push(o.value), a), [])      
console.log(filtered)

这篇关于根据值从对象数组中选择一个属性:Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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