Search code examples
javascriptangularjslodash

How to push id of parent object to child objects?


I have an array of object which has an inner array of object, I want to push the id of parent object to each child object.

   a = [
        {id: 'abc', stage: [{name: 'car' , value: '123'},{name: 'bus' , value: '345'},{name: 'truck' , value: '567'}],
        {id: 'def', stage: [{name: 'bike' , value: '890'},{name: 'cycle' , value: '123'},{name: 'car' , value: '456'}]}
    ]

expected output = [
    {name: 'car' , value: '123', id: 'abc'},{name: 'bus' , value: '345', 'abc'},{name: 'truck' , value: '567', 'abc'}, {name: 'bike' , value: '890', id: 'def'},{name: 'cycle' , value: '123',id: 'def',id: 'def'},{name: 'car' , value: '456', id: 'def'}
]

Im able to get the only the stage but not able to push id to each object. pls help

const getAllStages = [].concat(...map(a, el => el.stage));
console.log(getAllStages )

Solution

  • Use .map() again to add el.id to each element of el.stage.

    You can use .flatMap() in the outer mapping to concatenate all the results into a single array.

    const a = [
        {id: 'abc', stage: [{name: 'car' , value: '123'},{name: 'bus' , value: '345'},{name: 'truck' , value: '567'}]},
        {id: 'def', stage: [{name: 'bike' , value: '890'},{name: 'cycle' , value: '123'},{name: 'car' , value: '456'}]}
    ]
    
    result = a.flatMap(({
      id,
      stage
    }) => stage.map(s => ({
      id: id,
      ...s
    })));
    
    console.log(result);