Home > OS >  Flatten inner array but assign outer properties
Flatten inner array but assign outer properties

Time:01-29

I have an input like this:

var input = [
    {
        "inner_array": [
            {
                "inner_data": "inner_data1"
            },
            {
                "inner_data": "inner_data2"
            }
        ],
        "outer_data": "outer_data",
    }
];

And I'd like to process it so it becomes this.

var output = [
    {
        "inner_data": "inner_data1",
        "outer_data": "outer_data",
    },
    {
        "inner_data": "inner_data2",
        "outer_data": "outer_data",
    }
];

In words: I'd like to flatten an inner array, while still keeping the outer array's properties. Does this have an easy solution (with built in lambda array functions), or should I write a function myself which handles this?

CodePudding user response:

You could use .flatMap() on your input array to loop over each object, along with an inner .map() to map each inner_array to a new object. The new object can be a combination of the outer_data value along with the inner_data value. The .flatMap() method will then merge all returned objects from the inner .map() calls for each object within input into one resulting array:

const input = [{ "inner_array": [{ "inner_data": "inner_data1" }, { "inner_data": "inner_data2" } ], "outer_data": "outer_data", }];

const res = input.flatMap(obj => obj.inner_array.map(inner => ({
  ...inner,
  outer_data: obj.outer_data
})));
console.log(res);

  •  Tags:  
  • Related