Reputation: 119
I want to compare 2 array of objects and update the matching object as well as total count in the object
let arr1 = [{status: 'Total', count: 0, text: 'Total applications'},
{status: 'submitted', count: 0, text: 'Applications submitted'},
{status: 'Rejected', count: 0, text: 'Applications rejected'}]
let arr2 = [
{status: "submitted", count: 20} ,
{status: "Rejected", count: 10}
]
function
let finalResult = arr2.map(function(a){
var result=arr1.filter(b=> a.status==b.status ? {...a, count:b.count} : arr1[0].count:arr1[0].count );
return result
})
Final Result should be like this:
[{status: 'Total', count: 30, text: 'Total applications'},
{status: 'submitted', count: 20, text: 'Applications submitted'},
{status: 'Rejected', count:10, text: 'Applications rejected'}
]
Upvotes: 2
Views: 55
Reputation: 63524
First find the object with the Total
status. Then loop over the second array of objects, find each object's index within the first array, update the count of the object, then finally update the total count.
let arr1=[{status:"Total",count:0,text:"Total applications"},{status:"submitted",count:0,text:"Applications submitted"},{status:"Rejected",count:0,text:"Applications rejected"}],arr2=[{status:"submitted",count:20},{status:"Rejected",count:10}];
let total = arr1.find(obj => obj.status === 'Total');
for (const obj of arr2) {
const { count } = obj;
const index = arr1.findIndex(o => {
return o.status === obj.status
});
arr1[index].count = count;
total.count += count;
}
console.log(arr1)
Additional documentation
Upvotes: 1
Reputation: 37755
You can simply loop through second array and build a hash map and also find total value. now just loop over first array and update values accordingly
let arr1 = [{status: 'Total', count: 0, text: 'Total applications'},{status: 'submitted', count: 0, text: 'Applications submitted'},{status: 'Rejected', count: 0, text: 'Applications rejected'}]
let arr2 = [{status: "submitted", count: 20} ,{status: "Rejected", count: 10}]
let total = 0;
let obj = {}
// finding total and build hash map
arr2.forEach(data => {
obj[data.status] = obj[data.status] || data
total += data.count
})
// loop over first array and update count accordingly
let final = arr1.map(data => {
if(data.status === 'Total'){
return {...data, count: total}
} else if(data.status in obj){
return {...data, ...obj[data.status]}
} else {
return data
}
})
console.log(final)
Upvotes: 1