javascript | 对象分组

IT技术 javascript object merge grouping
2021-02-06 02:06:03

我有一个对象。它看起来像下面:

[
  {
    "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'
    }]
}

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

6个回答

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);

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

尝试这样的事情:

function groupBy(collection, property) {
    var i = 0, val, index,
        values = [], result = [];
    for (; i < collection.length; i++) {
        val = collection[i][property];
        index = values.indexOf(val);
        if (index > -1)
            result[index].push(collection[i]);
        else {
            values.push(val);
            result.push([collection[i]]);
        }
    }
    return result;
}

var obj = groupBy(list, "group");

请记住,Array.prototype.indexOf在 IE8 及更早版本中没有定义,但有常见的 polyfill。

我知道这是旧的,但我认为有些人可能会偶然发现这一点,并希望必须将值分组为键,使用相同的函数只需修改 if else 部分,如下所示: if (index > -1) result[val].push(collection[i]); else { values.push(val); result[val] = []; result[val].push([collection[i]]); }
2021-03-29 02:06:03
如何将 0、1 等更改为键名,例如“组”
2021-04-09 02:06:03

如果您喜欢使用 ES6 Map,那么这适合您:

function groupBy(arr, prop) {
    const map = new Map(Array.from(arr, obj => [obj[prop], []]));
    arr.forEach(obj => map.get(obj[prop]).push(obj));
    return Array.from(map.values());
}

const data = [{ 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" }];
	
console.log(groupBy(data, "group"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Map实例是根据从输入数组生成的键/值对创建的。键是要分组的属性的值,这些值被初始化为空数组。

然后填充这些数组。最后返回地图的值(即那些填充的数组)。

有人能帮我分解一下吗:obj => [obj[prop], []]
2021-03-21 02:06:03
@AnkitAgarwal,这是一个函数(箭头函数语法)。它接受一个参数 ( obj) 并返回一个包含两个条目的数组。第一个条目将具有值obj[prop](要分组的属性值)。第二个条目是一个空数组。此函数作为回调参数传递给Array.from,它将为 中的每个对象调用它arrMap构造可以处理小对这种阵列,所以new Map将获得的每个组的键,和对应的值将是为每个的空数组。
2021-04-04 02:06:03

如果您在应用程序中使用 underscore.js,那么您只需执行以下操作:

var groups = _.groupBy(data, 'group'); // data is your initial collection

或者,如果您不想使用任何库,那么您可以自己使用:

var groups = { };
data.forEach(function(item){
   var list = groups[item.group];

   if(list){
       list.push(item);
   } else{
      groups[item.group] = [item];
   }
});

您可以在http://jsfiddle.net/nkVu6/3/ 中看到这两个示例

使用reducefilter

假设您的初始数组被分配给 data

data.reduce((acc, d) => {
    if (Object.keys(acc).includes(d.group)) return acc;

    acc[d.group] = data.filter(g => g.group === d.group); 
    return acc;
}, {})

这会给你类似的东西

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