Alan Jenshen
Alan Jenshen

Reputation: 3239

Add new property to existing array of object from another array

I don't know how to write the title properly, pardon me on that.

Basically I have a list of array of object that's coming from a place, I need to map them together. How how with my code below I can't make it.

const person = [
  {name:'hello',id:1},
  {name:'javascript',id:2},
  {name:'world',id:3}
];

const selected = [2,3];


const normalized = person.map((obj,i) => obj.id === selected[i] ? Object.assign({}, obj, {checked:true}) : obj);

console.log(normalized)

https://jsfiddle.net/q9g0kazx/1/

I need to add an extra property base on the selected array. Why above code doesn't work?

Upvotes: 2

Views: 2625

Answers (2)

Mosh Feu
Mosh Feu

Reputation: 29347

If I understand you correctly, just iterate through the array using forEach and add the property if needed.

const person = [
   {name: 'hello', id: 1},
   {name: 'javascript',id: 2},
   {name: 'world',id: 3}
];

const selected = [2,3];

person.forEach(p => {
  if (selected.includes(p.id)) {
    p.checked = true;
  }
});

console.log(person);

Or you can use map like this:

const person = [
   {name: 'hello', id: 1},
   {name: 'javascript',id: 2},
   {name: 'world',id: 3}
];

const selected = [2,3];

person.map(p => {
  if (selected.includes(p.id)) {
    p.checked = true;
  }
  return p;
});

console.log(person);

Notice that you have to return the object (person in our case)

Upvotes: 3

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

You can do this:

Check if the the id in the array is present in the selected array by:

selected.includes(obj.id)

So, includes returns true if the obj.id was present in the selected array. If present(yes) then your Object.assignpart of code executes.

The reason your code was not working was because your person array and selected array don't have same number of elements(count) and perhaps not in the order as well. So person[0] id which is 1 doesn't match with selected[0] id which 2 and so on.

const person = [{
    name: 'hello',
    id: 1
  },
  {
    name: 'javascript',
    id: 2
  },
  {
    name: 'world',
    id: 3
  }
];

const selected = [2, 3];

const normalized = person.map((obj, i) => selected.includes(obj.id) ? Object.assign({}, obj, {
  checked: true
}) : obj);

console.log(normalized);

Upvotes: 0

Related Questions