我们如何从数组中提取特定字段的值(我想提取id值)
[
{id:1, added: true, name: 'Book'}, -> I want to extract id value!
{id:2, added: true, name: 'Desk'},
{id:5, added: true, name: 'Rock'},
{id:3, added: false, name: 'Rock'},
{id:7, added: false, name: 'Rock'},
{id:8, added: false, name: 'Rock'},
]
并创建一个包含值的数组。 (仅在添加的字段为真时)
预期输出为[1, 2, 5]
。
当我们得到[]空数组时,如果能抓住边缘情况会很棒。
请随意使用lodash(如果它比vanila javascript更快更简单)
答案 0 :(得分:3)
您可以将Array#filter与Array#map功能结合使用
const arr = [
{id:1, added: true, name: 'Book'},
{id:2, added: true, name: 'Desk'},
{id:5, added: true, name: 'Rock'},
{id:3, added: false, name: 'Rock'},
{id:7, added: false, name: 'Rock'},
{id:8, added: false, name: 'Rock'},
];
const mappedArr = arr.filter(item => item.added).map(item => item.id);
console.log(mappedArr);

答案 1 :(得分:3)
答案 2 :(得分:1)
const arr = [
{id:1, added: true, name: 'Book'},
{id:2, added: true, name: 'Desk'},
{id:5, added: true, name: 'Rock'},
{id:3, added: false, name: 'Rock'},
{id:7, added: false, name: 'Rock'},
{id:8, added: false, name: 'Rock'},
];
arr.reduce((prev, curr) => {
if (curr.added) {
return [...prev, curr.id];
}
return prev;
}, []);
答案 3 :(得分:1)
您可以使用array#reduce
并检查added
属性,如果true
将id
添加到累加器。
var data = [ {id:1, added: true, name: 'Book'}, {id:2, added: true, name: 'Desk'}, {id:5, added: true, name: 'Rock'}, {id:3, added: false, name: 'Rock'}, {id:7, added: false, name: 'Rock'}, {id:8, added: false, name: 'Rock'}],
result = data.reduce((r, {id, added}) => {
if(added)
r.push(id);
return r;
}, []);
console.log(result);