创建阵列有条件(JavaScript)的
我们如何从(我想提取的值id)创建阵列有条件(JavaScript)的
[ {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)
回答:
你只可以使用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);
回答:
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;
}, []);
回答:
您可以使用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);
回答:
首先filter出具有added
为假则map整个结果得到id
项目:
let result = _(data) .filter('added')
.map('id')
.value();
以上是 创建阵列有条件(JavaScript)的 的全部内容, 来源链接: utcz.com/qa/260319.html