0

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.

4
  • Also remove the 'else{finalArr.push(Object.assign(item, item1));};' Commented Aug 26, 2017 at 9:53
  • Then only matched values are coming. Commented Aug 26, 2017 at 9:53
  • Oh i see what you mean Commented Aug 26, 2017 at 9:54
  • I need if email is matched for both array then both array data will merge otherwise what ever the data are in one single array that will push to finalArr. Commented Aug 26, 2017 at 9:58

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.