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