J
J
jjsplash2021-12-01 23:14:00
JavaScript
jjsplash, 2021-12-01 23:14:00

How to get values ​​from an array of objects by id?

Hello, help with advice.
There is an array of NPL epl commands (for each command):

points: 30
position: 1
result: "Champions League"
status: "Promotion"
team_id: 2524

But there are no command names here.
There is an array with id from the epl array and the corresponding id of command names:
let teamNames = [ 
  { id: 2522, name: 'Arsenal' },
  { id: 2520, name: 'Aston Villa' },
  { id: 2513, name: 'Burnley' },
  { id: 2518, name: 'Brighton' },
  { id: 2537, name: 'Brentford' },
  { id: 2524, name: 'Chelsea' },
  { id: 2515, name: 'Crystal Palace' },
  { id: 2516, name: 'Everton' },
  { id: 2546, name: 'Leeds Utd' },
  { id: 12424, name: 'Leicester City' },
  { id: 2509, name: 'Liverpool' },
  { id: 12400, name: 'Manchtester City' },
  { id: 2523, name: 'Manchester Utd' },
  { id: 849, name: 'Newcastle Utd' },
  { id: 2510, name: 'Norwich City' },
  { id: 12423, name: 'Southampton' },
  { id: 12295, name: 'Tottenham' },
  { id: 2517, name: 'Watford' },
  { id: 12401, name: 'West Ham' },
  { id: 850, name: 'Wolverhampton' }
];

The question is: how to get team names from the teamNames array by the corresponding id and add these names to the epl array? I would be grateful for any hint!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-12-01
@jjsplash

Make an object from teamNames, where id will be the keys:

const teamNamesObj = Object.fromEntries(teamNames.map(n => [ n.id, n.name ]));

Extract names from this object:
const eplWithNames = epl.map(n => ({ ...n, name: teamNamesObj[n.team_id] }));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question