Home > OS >  Loop through array of objects and assign parent object to each child array of object using javascrip
Loop through array of objects and assign parent object to each child array of object using javascrip

Time:11-01

I have a array of object as follows. Currently there is only one object but invocations has an array of objects. Depending on how many array of objects we have for invocations, we want to update the main array of objects. For e.g. if there are 2 objects in invocations, i want to separate those 2 invocations and replicate their parent object for both invocations. This is not a regular iteration of array of objects and thats why i am not able to get the desired result. Any help is appreciated

const input = [
    {
        "name": "Test Data",
        "invocations": [
            { "invocationId": "123" },
            { "invocationId": "125" },
        ]
    },
]
const output = [
    {
        "name": "Test Data",
        "invocations": [
            { "invocationId": "123" },
        ]
    },
    {
        "name": "Test Data",
        "invocations": [
            { "invocationId": "125" },
        ]
    }
]

CodePudding user response:

Here is a working example non-one-liner though!

For each object inside your array, you loop through the invocations property array and push each object inside a temp array along with all the other properties.

Then this array is concatenated with the final array.

const input = [
    {
        "name": "Test Data",
        "invocations": [
            { "invocationId": "123" },
            { "invocationId": "125" },
        ]
    },
]

let finalArray = []

Object.values(input).forEach(obj => {
  let arr = []
  obj.invocations.forEach(invoc => arr.push({...obj, invocations: [ invoc ]}))
  finalArray = finalArray.concat(arr)
});

console.log(finalArray)

CodePudding user response:

This will do it:

const splitInvocations = array => array.reduce((result, obj) => [...result, ...obj.invocations.map(invocation => ({ ...obj, invocations: [invocation] }))], []);

First, we loop through the array with reduce. We then map each invocation and return the parent object with a replaced value for the property invocations. We concat the reduce accumulator with the output of map using spread syntax.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

  • Related