0

i have an array of objects like below,

data: [
    {
      name: 'name1',
      id: '1',
      description: 'name 1 description',
    }, 
    {
      name: 'name2',
      id: '2',
      description: 'name 2 description',
    },
    {
      name: 'name3',
      id: '3',
      description: 'name 3 description',
    },
]

i have an array consisting of ids like so

const id_list = ['1','2'];

Now i want to retrieve the id and name from data array object whose id matches with id_list

so the expected output is

const new = [
  {
    id: '1',
    name: 'name1',
  },
  {
    id: '2',
    name: 'name2',
  }
]

i am new to using react, javascript or typescript. could someone help me solve this. thanks.

what i have tried?

i know that to filter the value based on one value

so if i have to filter based on one id say '1' i can do

const new = data.filter((item) => id === item.id);

but in my case i want to filter all items which match the id_list array and should retrieve only matching object name and id and put it to a array.

stackuser
  • 199
  • 1
  • 13
  • `const newArr = id_list.map(id => data.find(item => item.id === id))` –  Feb 08 '21 at 12:32

1 Answers1

0

You can use the map function with a find method to map every id of id_list to the corresponding object in data

const result = id_list.map((id) => data.find((d) => d.id === id));

After that you have all objects that were found by ids in result. You can either only use the props you want or map again and get only the required properties.

const final = result.map(({ id, name })=> ({ id, name }))
Julian Kleine
  • 1,539
  • 6
  • 14