繁体   English   中英

从对象数组中收集数据并将它们放入新的对象数组中

[英]collecting data from an array of objects & put them in a new array of objects

我有一个名为 Lines 的对象数组。 Lines数组位于rows数组内,而 rows 数组位于tabs数组内。 我想从行数组中获取一些数据并将它们放入另一个名为colors的数组中

数组看起来像这样----

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

我想从lines数组中收集数据并将它们放入另一个名为“ colors ”的数组中

看起来像这样---

colors:  [{
          "selectedColor": "white",
          "selectedQty": 0,
          "selectedUnit": "1",

        }, {
          "selectedColor": "black",
          "selectedQty": "2",
          "selectedUnit": "3",
        },
        {
          "selectedColor": "black",
          "selectedQty": 0,
          "selectedUnit": "2",
        },
        {
          "selectedColor": "red",
          "selectedQty": 0,
          "selectedUnit": "",
        }
]

我正在使用vue.js 我该怎么做呢?

尝试这个:

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]
}, [])

你可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM