javascript - 根据属性的值将对象数组动态拆分为组

标签 javascript typescript

<分区>

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

这是一个输入示例:

`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 项目中) 但如果它使它变得非常容易,那么我并不反对。

提前致谢

最佳答案

使用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
}

关于javascript - 根据属性的值将对象数组动态拆分为组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50045676/

相关文章:

javascript - JQuery:如何在填写表单时实时显示错误?

javascript - jquery.post() : how do i honor a redirect from the server?

javascript - 将数组中的相似记录分组为一个键?

Angular 等待一个 promise 执行的循环,然后再继续下一个代码块

typescript - 带有嵌套对象的 Object.keys() : get correct types

javascript - 对 JSON 中的所有数据类型使用字符串是个好主意吗?

javascript - 传递数组中的 Angular 匹配值与页面上循环中的项目

javascript - 弹出图像并从现有 img 中查看大图

angular - 如何使用 Jasmine 为私有(private)方法编写 Angular/TypeScript 的单元测试

typescript - 如何恢复/安装定义为 devDependency 的 chai 类型