使用两个属性对对象进行分组

时间:2017-10-12 13:12:03

标签: javascript lodash

我有一个api在休息时返回以下对象:

对象

[
    {
      "attributes": {
        "State" : "Las vegas",
        "Period": 1991,
        "People": 6000,
        "Child" : 3000
      }
    },
    {
      "attributes": {
        "State" : "Las vegas",
        "Period": 2000,
        "People": 5000,
        "Child" : 1000
      }
    }
]

我需要一个类似的小组:

我之前的回复

{
  "People_2000": 
  [ 
    {
      "State" : "Las vegas",
      "People": 5000
    } 
  ], 
  "People_1991": 
  [ 
    {
      "State" : "Las vegas",
      "People": 6000
    } 
  ],
  "Child_1991": 
  [ 
    {
      "State" : "Las vegas",
      "Child": 3000
    } 
  ],
  "Child_2000": 
  [ 
    {
      "State" : "Las vegas",
      "Child": 1000
    } 
  ]
}

解释

用于在表中添加您的值。

我使用的是lodash版本:4.17.4

我也在版本中使用vue.js:2.3.3

我的分组不符合预期, https://jsfiddle.net/9fh0b3q7/4/

1 个答案:

答案 0 :(得分:1)

我们可以首先使用lodash#map获取所有属性,定义一个属性数组,您希望将属性数组与某个Period的特定前缀进行分组。使用lodash#reduce作为组合所有分组属性的方法。 lodash#group用于对每个映射属性进行分组,最后lodash#assign将所有属性及其各自的组包含在一个对象中。

var attributes = _.map(data, 'attributes');

var properties = ['State', 'People', 'Child'];

var result = _.reduce(properties, (acc, property) => _(attributes)
  .groupBy(v => property + '_' + v.Period)
  .assign(acc)
  .value(), 
  {}
);



var data = [
    {
      "attributes": {
        "State" : "Las vegas",
        "Period": 1991,
        "People": 6000
      }
    },
    {
      "attributes": {
        "State" : "Las vegas",
        "Period": 2000,
        "People": 5000
      }
    }
];

var attributes = _.map(data, 'attributes');

var properties = ['State', 'People', 'Child'];

var result = _.reduce(properties, (acc, property) => _(attributes)
  .groupBy(v => property + '_' + v.Period)
  .assign(acc)
  .value(), 
  {}
);

console.log(JSON.stringify(result, 0, 4));

.as-console-wrapper{min-height:100%;top:0;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;