2

I have an array with data:

const data = [
 {
 groupName: 'groupName1',
 types: [
 {
 name: 'name1',
 displayName: 'displayName1'
 },
 {
 name: 'name2',
 displayName: 'displayName2'
 },
 ]
 },
 {
 groupName: 'groupName2',
 types: [
 {
 name: 'name3',
 displayName: 'displayName3'
 },
 {
 name: 'name4',
 displayName: 'displayName4'
 },
 ]
 },
]

I need to transform this array so that an extra groupName field is added to each object. The 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 tried to do it through 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)

But this does not return the array that I need. Please tell me how I can transform this array so that each object has the correct structure? Thank you in advance!

Ori Drori
196k32 gold badges243 silver badges233 bronze badges
asked Sep 15, 2021 at 14:20

2 Answers 2

3

Replace the outer Array.map() call with Array.flatMap() to create a flat array, and return the result of the internal map call, and not the original item.

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.flatMap(({ types, groupName }) => 
 types.map(item => ({
 ...item,
 groupName
 }))
)
console.log(resultData)

answered Sep 15, 2021 at 14:22
Sign up to request clarification or add additional context in comments.

Comments

0

I would use reduce.

data.reduce((carry, {types, groupName}) => carry.concat(types.map(d => ({...d, groupName}))), []);
answered Sep 15, 2021 at 14:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.