有条件地创建数组(Javascript)

时间:2017-12-03 10:06:31

标签: javascript arrays lodash

我们如何从数组中提取特定字段的值(我想提取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更快更简单)

4 个答案:

答案 0 :(得分:3)

您可以将Array#filterArray#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)

首先filter输出added为false的项目,然后在结果中map以获取id

let result = _(data)
    .filter('added')
    .map('id')
    .value();

答案 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属性,如果trueid添加到累加器。

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);