2

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?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

2 Answers2

3

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)

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • 1
    Here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/includes?v=control It's actually, check if the index in `selected`, just like `selected.indexOf(p.id) > -1` – Mosh Feu May 14 '17 at 11:57
  • normally I will use indexOf, it's more common, what's the advantage of using includes than indexOf? – Alan Jenshen May 14 '17 at 14:02
  • I personally prefer a function that returns the type I expected e.g boolean. `indexOf` for check if exist seems like hack for me. Thankfully, es6 allowed it. – Mosh Feu May 14 '17 at 14:22
0

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);
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18