Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I replace array item with matched object keys?

Let’s say I have an array of id’s
const ids = [[1, 2, 3], [2, 3], [3]]

And have array with objects that have name for each id

const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
  ];

What is the most proper way to get ids = [["One", "Two", "Three"], ["Two", "Three"], ["Three"]], I’m worrying that nested mapping could cause performance issues.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a combination of map and find. There may be a more performant way of doing it, but I’d suggest worrying about that only if you run into performance issues :-

const ids = [[1, 2, 3], [2, 3], [3]];

const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
  ];

const mapped = ids.map(arr => arr.map(id => obj.find(obj => obj.id === id).name));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading