【问题标题】:dynamically split an array of objects into groups based on values of a property [duplicate]根据属性的值将对象数组动态拆分为组[重复]
【发布时间】:2018-10-07 07:29:15
【问题描述】:

我正在尝试动态地根据属性值将对象数组拆分为组。

这是一个输入示例:

`input = [
    {"name": "john", "location": "first"},
    {"name": "steve", "location": "first"},
    {"name": "paul", "location": "another"},
    {"name": "tony", "location": "random"},
    {"name": "ant", "location": "random"}
]`

以及所需的输出:

`solution(input, location) = [
    first:   [{"name": "john", "location": "first"},
              {"name": "steve", "location": "first"}],
    another: [{"name": "paul", "location": "another"}],
    random:  [{"name": "tony", "location": "random"},
              {"name": "ant", "location": "random"}]
]`

我不知道 location 可以是什么值(但我知道键名)

我试图避免使用任何外部库, (这是在一个 Angular 5 项目中) 但如果它使事情变得更容易,那么我并不反对。

提前致谢

【问题讨论】:

  • 使用.concat(arr, arr2)
  • @Karabah 你确定你读对了这个问题吗?

标签: javascript typescript


【解决方案1】:

为此使用Array#reduce

const input = [{"name":"john","location":"first"},{"name":"steve","location":"first"},{"name":"paul","location":"another"},{"name":"tony","location":"random"},{"name":"ant","location":"random"}];

const group = input.reduce((acc, item) => {
  if (!acc[item.location]) {
    acc[item.location] = [];
  }

  acc[item.location].push(item);
  return acc;
}, {})

console.log(group);

编辑 1

如果你想对结果进行迭代,你可以像这样使用for...of 循环和Object.entries

for (let [location, persons] of Object.entries(group)) {
  console.log(location, persons);
  // do your stuff here
}

【讨论】:

  • 谢谢!那是超级快..我一直在努力让我的头绕地图并减少,但这有帮助!
  • 我刚刚注意到这个答案的结果不是一个数组而是一个对象。我想创建一个包含结果的数组,以便可以对其进行迭代...
猜你喜欢
  • 2019-05-29
  • 2019-12-28
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 2016-11-08
相关资源
最近更新 更多