I have the following object:
const original = [{
"key-8": {
"some object"
}
},
{
"key-12": {
"some object"
}
},
{
"key-12": {
"some object"
}
},
{
"key-1": {
"some object"
}
},
{
"key-8": {
"some object"
}
}
]
As you can see I have two objects with key-8
and two with key-12
. I would like to combine them (the order does not matter) so the output will be:
{
{
"key-12": [{
"some object"
},
{
"some object"
}
]
}, {
"key-1": {
{
"some object"
}
},
{
"key-8": [{
"some object"
},
{
"some object"
}
]
}
}
}
I cannot make it works no matter what I try. I used reduce
, I used regular forEach
and other "hacks" simple do not work because TypeScript does not like them.
Can someone help please?
try this
const orig = [ { "key-8": { "key": "...", "value": "...", "info": "..." } }, { "key-12": { "key": "...", "value": "...", "info": "..." } }, { "key-12": { "key": "...", "value": "...", "info": "..." } }, { "key-1": { "key": "...", "value": "...", "info": "..." } }, { "key-8": { "key": "...", "value": "...", "info": "..." } } ]; const result = orig.reduce(function (r, a) { const { key, ...others } = Object.values(a)[0]; r[Object.keys(a)] = r[Object.keys(a)] || []; r[Object.keys(a)].push(others); return r; }, Object.create(null)); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.