并添加主阵列领域和子阵

并添加主阵列领域和子阵

本文介绍了由阵列组,并添加主阵列领域和子阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个沉重的数组是这样的:

I have a heavy array like this:

[
  {Id: 1, Name: 'Red', optionName: 'Color'},
  {Id: 2, Name: 'Yellow', optionName: 'Color'},
  {Id: 3, Name: 'Blue', optionName: 'Color'},
  {Id: 4, Name: 'Green', optionName: 'Color'},
  {Id: 7, Name: 'Black', optionName: 'Color'},
  {Id: 8, Name: 'S', optionName: 'Size'},
  {Id: 11, Name: 'M', optionName: 'Size'},
  {Id: 12, Name: 'L', optionName: 'Size'},
  {Id: 13, Name: 'XL', optionName: 'Size'},
  {Id: 14, Name: 'XXL', optionName: 'Size'}
]

我需要做的就是将它们分组按 OPTIONNAME ,并有两排主阵列像这样:

What I need to do is to group them by optionName and have two row in the main array like this:

[
  {
    Name: 'Color',
    Data:[{Id: 1, Name: 'Red'},
          {Id: 2, Name: 'Yellow'},
          {Id: 3, Name: 'Blue'},
          {Id: 4, Name: 'Green'},
          {Id: 7, Name: 'Black'}]
  }, {
    Name: 'Size',
    Data:[{Id: 8, Name: 'S'},
          {Id: 11, Name: 'M'},
          {Id: 12, Name: 'L'},
          {Id: 13, Name: 'XL'},
          {Id: 14, Name: 'XXL'}]
  }
]

如何做在JavaScript?

How to do it in javascript?

推荐答案

这是一个片段,我写了这些种情况。您可以将此功能添加到您所有的数组:

This is a snippet I wrote for these kind of situations. You can add this functionality to all of your arrays:

Object.defineProperty(Array.prototype, 'group', {
  enumerable: false,
  value: function (key) {
    var map = {};
    this.forEach(function (e) {
      var k = key(e);
      map[k] = map[k] || [];
      map[k].push(e);
    });
    return Object.keys(map).map(function (k) {
      return {key: k, data: map[k]};
    });
  }
});

您可以使用它像这样。你可以通过它定义你想怎么组数据的功能。

You can use it like this. You can just pass a function which defines how you want to group your data.

var newArray = arr.group(function (item) {
  return item.optionName;
});

如果您有需要,可以更换 {关键字:k,数据:地图[K]} {名称:K,数据:地图[K]}

If you need, you can replace {key: k, data: map[k]} with {Name: k, Data: map[k]}.

这也是code以上的更紧凑ES6版本:

This is also more compact ES6 version of the code above:

Object.defineProperty(Array.prototype, 'group', {
  enumerable: false,
  value: function (key) {
    var map = {};
    this.map(e => ({k: key(e), d: e})).forEach(e => {
      map[e.k] = map[e.k] || [];
      map[e.k].push(e.d);
    });
    return Object.keys(map).map(k => ({key: k, data: map[k]}));
  }
});

使用这样的:

var newArray = arr.group(item => item.optionName))

这篇关于由阵列组,并添加主阵列领域和子阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:23