merry-go-round
merry-go-round

Reputation: 4625

Create array conditionally (Javascript)

How do we extract the specific field's value from the array (I want to extract id value)

[
    {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'},
]

and create an array with the values. (only if the added field is true)

Expected Output will be [1, 2, 5].

It will be great if we can catch the edge case when we are getting [] empty array.

Please feel free to use lodash (if it's faster and simple than vanila javascript)

Upvotes: 0

Views: 98

Answers (4)

Gruff Bunny
Gruff Bunny

Reputation: 27976

First filter out the items that have added as false then map across the result to get the id:

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

Upvotes: 3

Hassan Imam
Hassan Imam

Reputation: 22544

You can use array#reduce and check for the added property, if it is true add the id to accumulator.

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

Upvotes: 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;
}, []);

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

You just can use Array#filter combined with Array#map function

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

Upvotes: 3

Related Questions