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 transform the data from one schema to other schema?

i am trying to convert the given data into other format but couldn’t do it.

input:

const arr= [{acc:"12345",address:{state:"tx",zip:"9999"}},
            {acc:"54321",address:{state:"tx",zip:"9999"}},
            {acc:"67891",address:{state:"ca",zip:"8888"}},
            {acc:"19876",address:{state:"ca",zip:"8888"}}]

expected o/p:

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

[
  {
  address: '{state:"tx",zip:"9999"}',
  accounts: ["12345","54321"]
   },
  {
  address: '{state:"ca",zip:"8888"}',
  accounts: ["67891","19876"]
   },

]

this is what i have tried

const arr= [{acc:"12345",address:{state:"tx",zip:"9999"}},
            {acc:"54321",address:{state:"tx",zip:"9999"}},
            {acc:"67891",address:{state:"ca",zip:"8888"}},
            {acc:"19876",address:{state:"ca",zip:"8888"}}]

let res = {}

arr.forEach(item=>{
  const formattedAddress = JSON.stringify(item.address) ;
  if(!res[formattedAddress]){
  res[formattedAddress] = []
  }
})

for(let i in res){
  arr.forEach(item=>{
    const formattedAddress = JSON.stringify(item.address);
    if(formattedAddress === i){
      res[i].push(item.acc)
    }
  })
}

console.log(res)

>Solution :

Group into an object or Map indexed by <state>_<zip>, then take the values of the object.

const arr= [{acc:"12345",address:{state:"tx",zip:"9999"}},
            {acc:"54321",address:{state:"tx",zip:"9999"}},
            {acc:"67891",address:{state:"ca",zip:"8888"}},
            {acc:"19876",address:{state:"ca",zip:"8888"}}]

const groupedByAddress = {};
for (const { acc, address } of arr) {
  const key = address.state + '_' + address.zip;
  groupedByAddress[key] ??= { address, accounts: [] };
  groupedByAddress[key].accounts.push(acc);
}
console.log(Object.values(groupedByAddress));
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