Home > OS >  Javascript merge nested list objects
Javascript merge nested list objects

Time:06-01

I want output like answer mentioned in the image

CodePudding user response:

you can use flat for that

const data = [[{color: 1}], [{color: 2}], [{color: 3}]]

console.log(data.flat())

CodePudding user response:

const list = [
  [{color1:'red',size1:21}],
  [{color2:'red',size2:21}],
  [{color3:'red',size3:21}],
  [{color4:'red',size4:21}]
]

// using built-in flat method
const ans = list.flat()
console.log(ans)

// using iterative approach (built-in map method)

const ans2 = list.map((eachArray) => eachArray[0])
console.log(ans2)


// ans1 and ans2 gives

/*

[
    {
        "color1": "red",
        "size1": 21
    },
    {
        "color2": "red",
        "size2": 21
    },
    {
        "color3": "red",
        "size3": 21
    },
    {
        "color4": "red",
        "size4": 21
    }
]

*/

Code : https://codesandbox.io/s/cocky-worker-dle269?file=/src/index.js:0-571

  • Related