4

Hello I would like to transform original array coming from API and change users color field into "primary" when their id matches. I've tried to run this code, however it retruns empty array

console.log(array.filter((item, i) => {
  return item.id === selected[i]
}))
// Original array
[
  {
    "id": "183",
    "fullName": "Simon Aaman",
    "color": "secondary"
  },
  {
    "id": "77",
    "fullName": "Dennis Bergkamp",
    "color": "secondary"
  },
  {
    "id": "80",
    "fullName": "Allison Bäcker",
    "color": "secondary"
  },
]
/array of ids
const selected = [77, 80]

Andreas
  • 21,535
  • 7
  • 47
  • 56
Verthon
  • 2,937
  • 3
  • 20
  • 32
  • 1
    `item.id` returns an ID as a string `selected[i]` is an array of *numbers*. They are [not equal according to `===`](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – VLAZ Jan 14 '20 at 11:49

3 Answers3

3

You can change the color using a map over your array and inside that you can just match against your selected ids.

const arr = [
  {
    "id": "183",
    "fullName": "Simon Aaman",
    "color": "secondary"
  },
  {
    "id": "77",
    "fullName": "Dennis Bergkamp",
    "color": "secondary"
  },
  {
    "id": "80",
    "fullName": "Allison Bäcker",
    "color": "secondary"
  },
];
const selected = [77, 80];

const result = arr.map((el) => {
  if(selected.includes(Number(el.id))){
    return {
      ...el,
      color: 'primary'
    }
  }
  return el;
});

console.log(result);
Also you had a problem with you code, you were strictly checking the ids using === which means you were looking for the type too (one was Number and one was a String), you could have done it using == which does not check for the type or just convert one of the ids to String/Number.
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
1

You need to use == or convert the string to Number since === will check datatype as well.

console.log(array.filter((item, i) => {
  return +item.id === selected[i]
}))

or

console.log(array.filter((item, i) => {
  return item.id == selected[i]
}))
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

You can try to filter from selected:

console.log(selected.map((s) => {
   return array.filter(el=>el.id ===`${s}`)
}))
Max
  • 1,020
  • 7
  • 13