Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare 2 objects and update the matching object in javascript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 [{status: 'Total', count: 30, text: 'Total applications'},
{status: 'submitted', count: 20, text: 'Applications submitted'},
{status: 'Rejected', count:10, text: 'Applications rejected'}
]

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading