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?
Advertisement
Answer
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)