lost9123193
lost9123193

Reputation: 11040

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.

Upvotes: 0

Views: 115

Answers (6)

nejdetckenobi
nejdetckenobi

Reputation: 624

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

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

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

Upvotes: 1

Bulent Vural
Bulent Vural

Reputation: 2688

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

Upvotes: 0

GiamPy
GiamPy

Reputation: 3570

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

Upvotes: 0

Weedoze
Weedoze

Reputation: 13953

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

Upvotes: 0

smnbbrv
smnbbrv

Reputation: 24581

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.

Upvotes: 3

Related Questions