简体   繁体   中英

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.

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.

Shortest solution using Array.prototype.forEach() and Array.prototype.indexOf() functions:

 var data = [{ name: "dog", present: false }, { name: "cat", present: true }, { name: "bird", present: false }], f = ["dog", "cat"]; data.forEach(function (o) { o.present = (f.indexOf(o.name) !== -1); }); console.log(data); 

You can use Array.map()

 var reflist = [{ name: "dog", present: false }, { name: "cat", present: true }, { name: "bird", present: false }]; var givenList = ["dog", "cat"]; reflist = reflist.map(function(elem){ if(givenList.indexOf(elem.name) !== -1) elem.present = true; return elem; }); console.log(reflist); 

Just another way to do it.

 var fields = [{ name: "dog", present: false }, { name: "cat", present: true }, { name: "bird", present: false }]; console.log(fields); ['dog', 'cat'].forEach(function (value) { fields.forEach(function (k) { if (k.name === value) { k.present = true; } }); }); console.log(fields); 

You'll need to loop the items of the ref data, compare each with the given set of items and build a new array of objects.

var wantedResult = [];
var keys = Object.keys(refData);
for(var i=0; i<keys.length; i++) {
    wantedResult.push({
        name:refData[keys[i]].name,         
        present:givenList.indexOf(refData[keys[i]].name) != -1
    });
}

Here is your one-liner:

referenceList.map((e) => { e.present = givenList.indexOf(e.name) > -1;})

Note that you'll modify referenceList and this line's return value will have no use for you. It will be just a list of undefined

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM