Home > Net >  How can I replace array item with matched object keys?
How can I replace array item with matched object keys?

Time:08-25

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.

CodePudding user response:

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));

CodePudding user response:

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

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

// dedicated object to keep association between id and names
let names = {} ;
obj.forEach( o => {
    names[ o.id ] = o.name ;
} ) ;

// map each sub array content to their real name
for( let i = 0; i <= ids.length-1; i  ){
    ids[i] = ids[i].map( id => names[id] ) ;
}

console.log( ids ) ;

=>

[ [ 'One', 'Two', 'Three' ], [ 'Two', 'Three' ], [ 'Three' ] ]
  • Related