簡體   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