In my data array, I have various groups and types:
const data = [
{
groupName: 'groupName1',
types: [
{
name: 'name1',
displayName: 'displayName1'
},
{
name: 'name2',
displayName: 'displayName2'
},
]
},
{
groupName: 'groupName2',
types: [
{
name: 'name3',
displayName: 'displayName3'
},
{
name: 'name4',
displayName: 'displayName4'
},
]
},
]
My goal is to modify this data array by adding a groupName field to each object. The desired output should be an array with objects as shown below:
const resultData = [
{
groupName: 'groupName1',
name: 'name1',
displayName: 'displayName1'
},
{
groupName: 'groupName1',
name: 'name2',
displayName: 'displayName2'
},
{
groupName: 'groupName2',
name: 'name3',
displayName: 'displayName3'
},
{
groupName: 'groupName2',
name: 'name4',
displayName: 'displayName4'
},
]
I attempted to achieve this using the map array method
const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]
const resultData = data.map((item) => {
item.types.map((item1) => {
return {
...item1,
groupName: item.groupName
}
})
return item
})
console.log(resultData)
However, this approach did not provide the desired array. Can you suggest an alternative method to transform this array to have the correct structure? Thank you in advance!