I'm looking for an efficient way to rearrange an array of objects in JS. I need to combine two parameters from each object into a single object, where the gwdetailsid value is the same.
Initial array:
{
"data": [
{
"gwdetailsid": "gw1",
"gwpname": "username",
"gwpvalue": "transalis"
},
{
"gwdetailsid": "gw1",
"gwpname": "password",
"gwpvalue": "secure_password@1"
},
{
"gwdetailsid": "gw2",
"gwpname": "username",
"gwpvalue": "tesco"
},
{
"gwdetailsid": "gw2",
"gwpname": "password",
"gwpvalue": "lemon_farmer_2"
}
]
}
The desired output array:
{
"gateways": [
{
"gwdetailsid": "gw1",
"username": "transalis",
"password": "secure_password@1"
},
{
"gwdetailsid": "gw2",
"username": "tesco",
"password": "lemon_farmer_2"
}
]
}
Effectively, your task comes down to transforming data array into gateways array.
You may employ Array.prototype.reduce() for that kind of job, to build up the Map with gwdetailsid property as a key, then extract .values() of that Map:
const data = [{gwdetailsid:"gw1",gwpname:"username",gwpvalue:"transalis"},{gwdetailsid:"gw1",gwpname:"password",gwpvalue:"secure_password@1"},{gwdetailsid:"gw2",gwpname:"username",gwpvalue:"tesco"},{gwdetailsid:"gw2",gwpname:"password",gwpvalue:"lemon_farmer_2"}],
gateways = [...data
.reduce((acc, {gwdetailsid, gwpname, gwpvalue} ) => {
const group = acc.get(gwdetailsid)
group
? group[gwpname] = gwpvalue
: acc.set(gwdetailsid, {gwdetailsid, [gwpname]: gwpvalue})
return acc
}, new Map)
.values()
]
console.log(gateways)
.as-console-wrapper{min-height:100%;}