根据属性值动态地将对象数组分成组[重复]

2024-04-07

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

这是输入的示例:

`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"}]
]`

我不知道位置的值(但我知道键名)

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

提前致谢


Use Array#reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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);

Edit 1

如果你想迭代结果,你可以使用for...of循环与Object.entries像这样:

for (let [location, persons] of Object.entries(group)) {
  console.log(location, persons);
  // do your stuff here
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据属性值动态地将对象数组分成组[重复] 的相关文章

随机推荐