Verthon
Verthon

Reputation: 3247

How to change original array based on other array

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]

Upvotes: 4

Views: 63

Answers (3)

Max
Max

Reputation: 1048

You can try to filter from selected:

console.log(selected.map((s) => {
   return array.filter(el=>el.id ===`${s}`)
}))

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115282

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

Upvotes: 1

Nicolae Maties
Nicolae Maties

Reputation: 2675

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.

Upvotes: 3

Related Questions