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

How to merge objects and append it into new array if object values are same using JavaScript?

I have this kind of data, my goal is to find all same request_id values in the given objects, merge it to one object and append its unique_id into one array, How can I get this result?

let fakeData = {
    "622b1e4a8c73d4742a66434e212":{
      request_id: "1",
      uique_id:'001'
    },
    "622b1e4a8c73d4742a6643423e54":{
        request_id: "1",
        uique_id:'002'
    },
    "622b1e4a8c73d4742a6643423e23":{
        request_id: "2",
        uique_id:'003'
    },
  }

  let parts = []

  for (const property in fakeData) {
      console.log(fakeData[property]);
  }


  //Result should be
  // [{request_id:'1', values:["001, 002"]}, {request_id:'2', values:["003"]}]

>Solution :

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

You can iterate over all the values using Object.values() and array#reduce. In the array#reduce group based on request_id in an object and extract all the values of these object using Object.values().

const fakeData = { "622b1e4a8c73d4742a66434e212": { request_id: "1", uique_id: '001' }, "622b1e4a8c73d4742a6643423e54": { request_id: "1", uique_id: '002' }, "622b1e4a8c73d4742a6643423e23": { request_id: "2", uique_id: '003' }, },
      output = Object.values(fakeData).reduce((r, {request_id, uique_id}) => {
        r[request_id] ??= {request_id, values: []};
        r[request_id].values.push(uique_id);
        return r;
      },{}),
      result = Object.values(output);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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