I am struggling to efficiently match and update objects from 2 arrays with different key combinations. Despite trying various .filter combinations, I have not been successful yet. My goal is to update the masterList based on the selectionList.
for (let selObj of selctionList) {
for (let obj of masterList) {
if (selObj['n'] == obj['name']) {
obj['checked'] = true;
obj['cost'] = selObj['r'];
obj['qty'] = (selObj['q'] ? selObj['q'] : 1);
break;
}
}
}
for (let obj of masterList) {
if (!obj['checked']) {
obj['checked'] = false;
}
}
Sample Data
`masterList =
[{"id":459,"cost":250,"name":"Coke"},
{"id":460,"cost":60,"name":"Cookies"},
{"id":461,"cost":100,"name":"Pizza"},
{"id":462,"cost":250,"name":"Bread"},
{"id":463,"cost":150,"name":"Sausage"},
{"id":464,"cost":150,"name":"Juice"}];
selectionList = [{"q":1,"r":350,"n":"Coke"}
{"q":2,"r":550,"n":"Bread"}]`
Output :
`[{"id":459,"cost":350,"name":"Coke", "checked" : true,"qty":1},
{"id":460,"cost":60,"name":"Cookies","checked" : false},
{"id":461,"cost":100,"name":"Pizza","checked" : false},
{"id":462,"cost":550,"name":"Bread","checked" : true,"qty":2},
{"id":463,"cost":150,"name":"Sausage","checked" : false},
{"id":464,"cost":150,"name":"Juice","checked" : false}]`