簡體   English   中英

按多個屬性分組對象並合並數組屬性

[英]Group objects by multiple properties and merge array property

在示例中,我使用每個到 go 到 select 字段並創建一個數據數組,我需要將 2 個屬性yearcabin分組,屬性months也是一個我想合並的數組,事情是我有點獲得想要的結果的麻煩:

JSFIDDLE: http://jsfiddle.net/tc39xu6b/2/

結果我得到:

[
  {
    "year": "2021",
    "cabin": "1",
    "months": [
      "1",
      "2"
    ]
  },
  {
    "year": "2021",
    "cabin": "1",
    "months": [
      "4"
    ]
  },
  {
    "year": "2021",
    "cabin": "2",
    "months": [
      "1",
      "2"
    ]
  },
  {
    "year": "2022",
    "cabin": "1",
    "months": [
      "1",
      "2"
    ]
  },
  {
    "year": "2022",
    "cabin": "1",
    "months": [
      "4"
    ]
  },
  {
    "year": "2022",
    "cabin": "2",
    "months": [
      "1",
      "2"
    ]
  }
]

這是我需要的結果:

{
  "2021": [
      {"cabin":1, "months": ["1", "2","4"]},
      {"cabin":2, "months": ["1", "2"]}
  ],
  "2022": [
      {"cabin":1, "months": ["1", "2","4"]},
      {"cabin":2, "months": ["1", "2"]}
  ]
}

所以,你已經完成了解決方案。

根據你所擁有的,我寫了一個分組 function:

 const addUnique=(arr1,arr2)=>{ arr2.forEach(item=>arr1.includes(item) || arr1.push(item)) return arr1; } const grouped= obj.reduce((groups,item)=>{ const yearItems=(groups[item.year]||[]) const cabinItem=yearItems.find(({cabin})=>cabin===item.cabin) const newCabinItem=cabinItem||{cabin:item.cabin}; newCabinItem.months=addUnique(newCabinItem.months||[],item.months); return {...groups, [item.year]: cabinItem? yearItems.map(yearItem => yearItem.cabin === item.cabin? newCabinItem: yearItem): yearItems.concat([newCabinItem]) } },{})

你可以看到它在這里工作: http://jsfiddle.net/9huwkz5L/

這是一個相當標准group by情況分組。 下面的代碼片段使用reduce()重構您的數組,但您可以將邏輯直接放在 function 中: http://jsfiddle.net/83st9wgh/

 const input = [{ "year": "2021", "cabin": "1", "months": ["1", "2"] }, { "year": "2021", "cabin": "1", "months": ["4"] }, { "year": "2021", "cabin": "2", "months": ["1", "2"] }, { "year": "2022", "cabin": "1", "months": ["1", "2"] }, { "year": "2022", "cabin": "1", "months": ["4"] }, { "year": "2022", "cabin": "2", "months": ["1", "2"] }]; const result = input.reduce((acc, { year, cabin, months }) => { const yearArray = (acc[year]??= []); let cIndex = yearArray.findIndex(o => o.cabin === cabin); if (cIndex === -1) { cIndex = yearArray.push({ cabin, months: [] }) - 1; } const monthsArray = yearArray[cIndex].months; yearArray[cIndex].months = [...new Set(monthsArray.concat(months))]; return acc; }, {}); console.log(JSON.stringify(result, null, 2));

暫無
暫無

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

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