根据值从对象数组中选择一个属性: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)