[Vuejs]-Collecting data from an array of objects & put them in a new array of objects

3๐Ÿ‘

โœ…

you can do something like this using flatMap

const data = {
  "tabs":[
    {
      "selectedHouseType":"1",
      "rows":[
        {
          "selectedDecor":"2",
          "lines":[
            {
              "selectedColor":"white",
              "selectedQty":0,
              "selectedUnit":"1"
            },
            {
              "selectedColor":"black",
              "selectedQty":"2",
              "selectedUnit":"3"
            }
          ]
        }
      ]
    },
    {
      "selectedHouseType":"select",
      "rows":[
        {
          "selectedDecor":"2",
          "lines":[
            {
              "selectedColor":"red",
              "selectedQty":0,
              "selectedUnit":""
            }
          ]
        }
      ]
    }
  ]
}

const lineColors = data.tabs.flatMap(t => t.rows.flatMap(r => r.lines))

console.log(lineColors)
๐Ÿ‘คR4ncid

3๐Ÿ‘

Try this :

const colors = tabs.reduce((acc, tab) => {
    const rows = tab.rows
    const lines = rows.reduce((acc, row) => {
        const lines = row.lines
        return [...acc, ...lines]
    }, [])
    return [...acc, ...lines]
}, [])
๐Ÿ‘คSilent observer

Leave a comment