JavaScript本机groupBy减少 [英] JavaScript native groupBy reduce

查看:65
本文介绍了JavaScript本机groupBy减少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript本机reduce,但是我想对分组稍作更改以获得我想要的结果. 我有一个数组如下:

I am using JavaScript native reduce, however I want to slightly change in the grouping to get my desired result. I have an array as follows:

const people = [
  {name: "John", age: 23, city: "Seattle", state: "WA"},
  {name: "Mark", age: 25, city: "Houston", state: "TX"},
  {name: "Luke", age: 26, city: "Seattle", state: "WA"},
  {name: "Paul", age: 28, city: "Portland", state: "OR"},
  {name: "Matt", age: 21, city: "Oakland", state: "CA"},
  {name: "Sam", age: 24, city: "Oakland", state: "CA"}
]

我要对其进行分组并将其更改为:

I want to group it and change it to this:

const arranged = [
  {
    city: "Seattle",
    state: "WA",
    persons: [
      { name: "John", age: 23 },
      {name: "Luke", age: 26}
    ]
  },
    {
    city: "Houston",
    state: "TX",
    persons: [
      {name: "Mark", age: 25}
    ]
  },
  {
    city: "Portland",
    state: "OR",
    persons : [
      {name: "Paul", age: 28}
    ]
  },
  {
    city: "Oakland",
    state: "CA",
    persons: [
      {name: "Matt", age: 21},
      {name: "Sam", age: 24}
    ]
  }
]

推荐答案

您可以使用函数reduce进行分组和构建所需的输出.

You can use the function reduce to group and build the desired output.

const people = [  {name: "John", age: 23, city: "Seattle", state: "WA"},  {name: "Mark", age: 25, city: "Houston", state: "TX"},  {name: "Luke", age: 26, city: "Seattle", state: "WA"},  {name: "Paul", age: 28, city: "Portland", state: "OR"},  {name: "Matt", age: 21, city: "Oakland", state: "CA"},  {name: "Sam", age: 24, city: "Oakland", state: "CA"}]

const result = Object.values(people.reduce((a, {name, age, city, state}) => {
  var key = [city, state].join('|');
  (a[key] || (a[key] = {city, state, persons: []})).persons.push({name, age});
  return a;
}, {}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于JavaScript本机groupBy减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆