0

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)

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for replying it late. But can we do this conditionally???? Sorry, I edited the question. I think you can solve it like a charm. Thanks
Add Array#filter first.
3

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

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.