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?
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"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.