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]

1
  • 1
    item.id returns an ID as a string selected[i] is an array of numbers. They are not equal according to === Commented Jan 14, 2020 at 11:49

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

You can try to filter from selected:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.