首页 > 解决方案 > 按多个属性分组对象并合并数组属性

问题描述

在示例中,我使用 each 来遍历选择字段并创建一个数据数组,我需要对 2 个属性进行分组year,并且cabin该属性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"]}
  ]
}

标签: javascriptarraysobjectgrouping

解决方案


所以,你已经到了解决方案的中途了。

从你所拥有的我写了一个分组函数:

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/


推荐阅读