I have the following object given:
{
"groupA": [
{data: 'foo'},
{data: 'bar'}
],
"groupB": [
{data: 'hi'},
{data: 'mom'}
]
}
I would like to append the parent object keys to all its array items like so:
{
"groupA": [
{data: 'foo', set: 'groupA'},
{data: 'bar', set: 'groupA'}
],
"groupB": [
{data: 'hi', set: 'groupB'},
{data: 'mom', set: 'groupB'}
]
}
How can I achieve this?
This is a immutable version that give you a new object using Object.fromEntries Object.entries and map
const data = {
"groupA": [{
data: 'foo'
},
{
data: 'bar'
}
],
"groupB": [{
data: 'hi'
},
{
data: 'mom'
}
]
}
const withGroup = Object.fromEntries(
Object.entries(data).map(([set, items]) => [set, items.map(i => ({ ...i,set}))])
)
console.log(withGroup)
You can do it simply by looping over the object and mapping the arrays, like this:
const data = {
"groupA": [
{data: 'foo'},
{data: 'bar'}
],
"groupB": [
{data: 'hi'},
{data: 'mom'}
]
};
Object.keys(data).forEach(key => {
data[key] = data[key].map(rec => ({...rec, set: key}));
})
console.log(data);
You can loop and set each item
const obj = {
"groupA": [
{data: 'foo'},
{data: 'bar'}
],
"groupB": [
{data: 'hi'},
{data: 'mom'}
]
};
Object.entries(obj).forEach(([key,val]) => val.forEach(item => item.set=key))
console.log(obj)