Search code examples
javascriptnode.jslodash

Merge array values with diffrent property names


I’ve two arrays of objects with name value and id

Array A

ArrayA:  [{
    name: ,
    value: ,
    key: 
},
];

I’ve another array of objects but with diffretns names of properties

ArrayB:  [{
    user: “userA” ,
    email: “emailA”,
    key:1: 
},
{
    user: “userB” ,
    email: “emailB”,
    key: 
},
];

Now I want to ThatArrayA will have the values from ArrayB. I mean user => name and email => value

ArrayA should have the following entries

  ArrayA:  [{
        name: “userA” ,
        value: “emailA”,
        key: 1
    },
        name: “userB” ,
        value: “emailB”,
        key: 1
    ]

I’ve tried to use map but without success, any idea what am I missing here?

ArrayA = ArrayB.map(((item: { name: string; value: string }) => (item.user, item.email))

I Can use a loop, there is better way to to it ?

Should I use lodash?


Solution

  • I think ArrayA is useless here, You can just use map() over ArrayB and return the Array with the properties you need.

    const ArrayB = [
      {
        user: "dani" ,
        email: "[email protected]",
        key:1 
      },
      {
        user: "john" ,
        email: "[email protected]",
        key:2
      }
    ]
    
    const res = ArrayB.map(({ user, email, key }) => ({
      name: user,
      value: email,
      key 
    }));
    
    console.log(res);