lost9123193 lost9123193 - 4 years ago 121
Javascript Question

Adding Objects to List in Javascript

I'm given the following data:

Reference List:



[{
name: "dog", present: false
}, {
name: "cat", present: true
}, {
name: "bird", present: false
}]


Given List:



["dog, cat"]


Wanted Result:



[{
name: "dog", present: true
}, {
name: "cat", present: true
}, {
name: "bird", present: false
}]


Right now I can produce the Wanted Result by creating 3 conditional statements and performing an
indexOf
. However, I'm wondering if there's a way to do that all in 1 line through something like lodash.

Answer Source

Is that what you need?

let reference = [{name:"dog", present:false}, {name:"cat", present:true}, {name:"bird", present:false }];
let list = ['dog', 'cat'];

let result = reference.map(item => ({
  name: item.name,
  present: list.indexOf(item.name) !== -1
}));

console.log(result);

It is logically doing the same you wrote, just utilizing the .map function for that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download