按多个属性对对象进行分组并合并数组属性

2022-08-05 00:00:00 arrays object grouping javascript

在示例中,我使用Each遍历选择字段并创建数据数组,我需要对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"]}
  ]
}

解决方案

这是相当正常的group by情况。下面的代码片段使用reduce()重构您的数组,但您可以直接将逻辑按原样放入函数中:http://jsfiddle.net/83st9wgh/

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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));

相关文章