'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:
[
{
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 1:[1]
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));
Solution 2:[2]
You could use a map with the stringified address as the key and an array as the accounts:
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 results = new Map<String, String[]>()
arr.forEach(item => {
const addressString = JSON.stringify(item.address)
const entries = results.get(addressString) || []
entries.push(item.acc)
results.set(addressString, entries)
})
results.forEach((val, key) => {
console.log({
address: key,
accounts: val
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 | Benno Grimm |
