javascript |对象分组

标签 javascript object merge grouping

我有一个对象。如下所示:

[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]

我想按组字段对这些数据进行分组并得到这个对象:

var obj = {
    0 = [
    {
       'group'   = 'Technical detals',
       'name'    = 'Display',
       'id'      = '60',
       'value'   = '4'
    },
    {
       'group'   = 'Technical detals',
       'name'    = 'OS',
       'id'      = '37',
       'value'   = 'Apple iOS'
    }],
    1   = [
    {
       'group'   = 'Manufacturer',
       'name'    = 'Manufacturer',
       'id'      = '58',
       'value'   = 'Apple'
    }]
}

如何对我的第一个对象进行分组?

最佳答案

Reduce非常适合这样的情况。给定下面的 list 是您的输入数据:

const list = [{
    'name': 'Display',
    'group': 'Technical detals',
    'id': '60',
    'value': '4'
  },
  {
    'name': 'Manufacturer',
    'group': 'Manufacturer',
    'id': '58',
    'value': 'Apple'
  },
  {
    'name': 'OS',
    'group': 'Technical detals',
    'id': '37',
    'value': 'Apple iOS'
  }
];

const groups = list.reduce((groups, item) => {
  const group = (groups[item.group] || []);
  group.push(item);
  groups[item.group] = group;
  return groups;
}, {});

console.log(groups);

如果你想不可变,你可以这样写 reduce:

const list = [{
    'name': 'Display',
    'group': 'Technical detals',
    'id': '60',
    'value': '4'
  },
  {
    'name': 'Manufacturer',
    'group': 'Manufacturer',
    'id': '58',
    'value': 'Apple'
  },
  {
    'name': 'OS',
    'group': 'Technical detals',
    'id': '37',
    'value': 'Apple iOS'
  }
];

const groups = list.reduce((groups, item) => ({
  ...groups,
  [item.group]: [...(groups[item.group] || []), item]
}), {});

console.log(groups);

取决于您的环境是否允许传播语法。

关于javascript |对象分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21776389/

相关文章:

javascript - Chrome 40 不支持 React setState 传播运算符

r - R:融合和合并数据

javascript - Javascript更改音频src

javascript - 仅特定文件路径的浏览器加载错误 - 内部服务器错误 500

javascript - AngularJS,无法添加模块

java - 我如何检查java中对象的内存使用情况

javascript:检查是否存在多个特定对象属性(也在coffeescript中)

java - 如何更新第二堂课中的变量totalCost

linux - 基于具有不同行号的公共(public)列合并两个txt文件

git - 根据文件类型选择 git mergetool