Home > Back-end >  JS - How to add key:value pairs from objects nested in arrays to other objects nested in another arr
JS - How to add key:value pairs from objects nested in arrays to other objects nested in another arr

Time:11-02

I know it has been countlessly asked and I assure you that I've read a lot of posts, articles, etc. and watched a lot of videos but nothing seem to click.

so there we go :

Here are 2 arrays with partial informations about every persons


let arr1 = [{id:00, name:Ben, city:Philadelphia}, {id:01, name:Alice, city:Frankfurt}, {id:02, name:Detlef, city:Vienna}]

let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}]

And there is the desired final result : an array including name, city and age of each persons

let arr3 = [{name:Ben, city:Philadelphia, age:39}, {name:Alice, city:Frankfurt, age:75 }, {name:Detlef, city:Vienna, age:18}]

What'the situation ? : Two arrays both containing objects. each nested object has an id. That id is the common key in each arrays of objects.

What do you want to do ? : I want to create a third array including informations from both arrays (from arr1 : name and city ; from arr2:age).

What have you tried so far ? : I couldn't manage to achieve anything worth showing. this minimal example is intended to show you a simple example of my current situation which is : I've got an array that is in the LocalStorage on one hand and an API on the other, both contain some infos regarding particular objects (let say persons). I want to create an array that will contain all the information regarding each person for easier manipulation afterward (DOM generation, etc.).

I've manage to store both arrays in two "local" arrays but the problem is still there: I can't figure out how to make an array where items are getting their key/value from two separate sources.

Thank you for your help !

CodePudding user response:

You can use reduce method on the arr with array as an inital value, and inside try to find the corrospending item with same id and destruct the object from the id and merge the two object with spread operator.

let arr1 = [{id:00, name:'Ben', city: 'Philadelphia' }, {id:01, name:'Alice', city:'Frankfurt'}, {id:02, name:'Detlef', city:'Vienna'}]

let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}]


const result = arr1.reduce((acc, { id: id1, ...rest1 }) => {
  const { id: id2, ...rest2 } = arr2.find(i => i.id === id1)
  acc.push({ ...rest1, ...rest2 })
  return acc;
}, [])

console.log(result)

CodePudding user response:

You can solve it in various ways, here first I have implemented a dict with key as id to get the value in O(1) while iterating arr2.

So the overall time complexity is O(n k) where n is len of arr1 and k is len of arr2.

let arr1 = [{id:00, name: "Ben", city: "Philadelphia"}, {id:01, name:"Alice", city:"Frankfurt"}, {id:02, name:"Detlef", city:"Vienna"}];

let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}];


const refMapById = arr1.reduce((refMap, {id, name, city}) => {
  refMap[id] = {name, city};
  return refMap;
}, {});

const result = arr2.reduce((resultArray, {id, age}) => [...resultArray, { ...refMapById[id],age}], []);

console.log(result);

Cheers!

CodePudding user response:

It will be worth creating a dictionary from one of the arrays anyway since using .find() inside of .reduce() adds an unnecessary nested loop. But instead of reducing the second array as was suggested you can simply .map() it into the result array, like so:

let arr1 = [{ id: 00, name: "Ben", city: "Philadelphia" }, { id: 01, name: "Alice", city: "Frankfurt" }, { id: 02, name: "Detlef", city: "Vienna" }];
let arr2 = [{ id: 02, age: 18 }, { id: 00, age: 39 }, { id: 01, age: 75 }];

const groupedById = arr1.reduce((group, person) => {
    group[person.id] = person;

    return group;
}, {});

const result = arr2.map((personPartFromSecondArray) => {
    const personPartFromFirstArray = groupedById[personPartFromSecondArray.id];

    if (typeof personPartFromFirstArray !== "undefined") {
        return { ...personPartFromFirstArray, ...personPartFromSecondArray }
    }

    return personPartFromSecondArray;
});

console.log(result);

  • Related