0

I have to arrays of objects arr1 = [....] arr2 = [....]

now i'd like to find matching object based of it's id and then copy the values from one to another I made this using for loops:

for (let newCampaignState of data) {
            for (let oldCampaignState of this.campaigns) {
                if (oldCampaignState.id === newCampaignState.id) {
                    oldCampaignState.name = newCampaignState.name;
                }
            }
        }

how could i do this using more functional programming?

filemonczyk
  • 1,613
  • 5
  • 26
  • 47
  • Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Erazihel May 04 '17 at 12:13

1 Answers1

4

You can use filter fuction:

Code

var arr1 = [{
  name: 'category1',
  id: '1'
}, {
  name: 'category3',
  id: '2'
}, {
  name: 'category2',
  id: '2'
}];

var arr2 = [{
  name: 'category2',
  id: '5'
}, {
  name: 'category2',
  id: '1'
}, {
  name: 'category2',
  id: '2'
}];


let filtered = [];

arr1.filter(function(newData) {
  return arr2.filter(function(oldData) {
      if (newData.id === oldData.id && newData.name === oldData.name) {
      filtered.push({
        'id': newData.id,
        'name': newData.name
      })
    }
  })
});

document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(filtered, null, 4)));
body {
  white-space: pre;
  font-family: monospace;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
Sumit Ridhal
  • 1,359
  • 3
  • 14
  • 30