A B
A B

Reputation: 174

how to map properties of two object arrays with different lengths in JavaScript

Being a newbie I have found this problem that I don't know to solve.

Given 2 arrays of different lengths I want to map the value of key total of arr2 over the value of key total of arr1 function of value of key grpId of arr1, as follow:

 arr1 = [{id: 1, grpId: 'x', total: null},
        {id: 2, grpId: 'x', total: null},
        {id: 3, grpId: 'x', total: null},
        {id: 4, grpId: 'y', total: null},
        {id: 5, grpId: 'y', total: null}];

 arr2 = [{id: 1, grpId: 'x', total: 3},
        {id: 2, grpId: 'y', total: 2}];

I need the result as below:

 arr1 = [{id: 1, grpId: 'x', total: 3},
        {id: 2, grpId: 'x', total: 3},
        {id: 3, grpId: 'x', total: 3},
        {id: 4, grpId: 'y', total: 2},
        {id: 5, grpId: 'y', total: 2}];

Upvotes: 0

Views: 610

Answers (2)

symlink
symlink

Reputation: 12218

Use Array.map() to loop through arr1, and inside that loop through arr2 and assign the total values:

let arr1=[{id:1,grpId:"x",total:null},{id:2,grpId:"x",total:null},{id:3,grpId:"x",total:null},{id:4,grpId:"y",total:null},{id:5,grpId:"y",total:null}],arr2=[{id:1,grpId:"x",total:3},{id:2,grpId:"y",total:2}];
        
        
let res = arr1.map(el1 => {
    arr2.forEach(el2 => {
        if(el2.grpId == el1.grpId){
            el1.total = el2.total
        }
    })
    return el1
})

console.log(res)

Upvotes: 1

Alex D
Alex D

Reputation: 692

Try this:

 const arr1 = [{id: 1, grpId: 'x', total: null},
        {id: 2, grpId: 'x', total: null},
        {id: 3, grpId: 'x', total: null},
        {id: 4, grpId: 'y', total: null},
        {id: 5, grpId: 'y', total: null}];

 const arr2 = [{id: 1, grpId: 'x', total: 3},
        {id: 2, grpId: 'y', total: 2}];

const output = arr1.map(entry => ({
    ...entry,
    total: arr2.find(a2 => a2.grpId === entry.grpId).total
}));

console.log(output);

Should see the output in your console window. (Developer tools of your browser).

Upvotes: 1

Related Questions