簡體   English   中英

組合數組內的所有數組

[英]Combine All Array Inside of Arrays

我在組合來自另一個數組的數組時遇到問題。

數據

   datas = [
      {
        "id": "22333",
        "name": "",
        "details": [
          {
            "value": 1
          },
          {
            "value": 2
          }
        ]
      },
      {
        "id": "4444",
        "name": "",
        "details": [
          {
            "value": 99
          },
          {
            "value": 66
          }
        ]
      }
    ]

預期產出

final = [
    {
      "value": 1
    },
    {
      "value": 2
    },
    {
        "value": 99
    },
    {
        "value": 66
    }
  ]

代碼

  datas.map((data) => ({ ...data.details}))

您可以使用flatMap而不是map

flatMap方法返回一個新數組,該數組通過將給定的回調函數應用於數組的每個元素,然后將結果展平一級而形成。 它與 map() 后跟一個深度為 1 的 flat() 相同,但比分別調用這兩個方法效率稍高。

 const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}]; const flattened = datas.flatMap(obj => obj.details); console.log(flattened);

datas.reduce((acc, val) => { return acc.concat(val.details) }, [])

您還可以在此處使用reduce

arr.reduce((acc, curr) => {
  acc.push(...curr.details);
  return acc;
}, [])

 const arr = (datas = [ { id: "22333", name: "", details: [ { value: 1, }, { value: 2, }, ], }, { id: "4444", name: "", details: [ { value: 99, }, { value: 66, }, ], }, ]); const result = arr.reduce((acc, curr) => { acc.push(...curr.details); return acc; }, []); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM