satya
satya

Reputation: 3560

Could not map two array using JavaScript/Node.js

I could not map two array of json data as per key value using JavaScript. My code is below:

 var userdata=[{'email':'[email protected]','name':'Rajj'},{'email':'[email protected]','name':'Rajesh'}];
        var userdata1=[{'email':'[email protected]','address':'rasukgarh'}];
        var finalArr=[];
        userdata.map(item => {
              userdata1.map(item1 => {
                if(item.email==item1.email){
                  finalArr.push(Object.assign(item, item1));
                }else{
                  finalArr.push(Object.assign(item, item1));
                }
              })
            })
            console.log('all Data',finalArr);
      }

Here my requirement is if same email id is present in both array then the additional data of second array will merge with first one. If 1st array has some data and based on the email value no data is present inside second array then in hat case only first array data will push to resultant array. Here my expected output is.

finalArr=[{'email':'[email protected]','name':'Rajj','address':'rasukgarh'},{'email':'[email protected]','name':'Rajesh'}]

But in my case I could not get like this.

Upvotes: 0

Views: 50

Answers (2)

Lucky Soni
Lucky Soni

Reputation: 6878

    var userdata = [{ 'email': '[email protected]', 'name': 'Rajj' }, { 'email': '[email protected]', 'name': 'Rajesh' }];
    var userdata1 = [{ 'email': '[email protected]', 'address': 'rasukgarh' }];
    userdata.map(function(item) {
        userdata1.map(function(item1) {
            if (item.email == item1.email) {
                // modify the original userdata array item
                Object.assign(item, item1);
            }
        })
    })
    console.log(userdata);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can use map() to create new array and find() to find objects with same email in second array and Object.assign() to create copy of object and assign objects from second array.

var userdata=[{'email':'[email protected]','name':'Rajj'},{'email':'[email protected]','name':'Rajesh'}];
var userdata1=[{'email':'[email protected]','address':'rasukgarh'}]

var result = userdata.map(function(e) {
  var find = userdata1.find(a => a.email == e.email);
  return Object.assign({}, e, find)
})

console.log(result)

Upvotes: 2

Related Questions