Grouping an object with two attributes

匆匆过客 提交于 2019-12-10 12:25:59

问题


i have an api in rest that return the following object :

The object

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

I need a group at the like with this :

My previous return

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

Explanation

For add in table yours values.

I am using the version of lodash : 4.17.4

Also am using vue.js at the version: 2.3.3

my grouping is not as expected, https://jsfiddle.net/9fh0b3q7/4/


回答1:


We can get all attributes first using lodash#map, define an array of properties that you want your array of attributes to be grouped with a certain prefix from a certain Period. Use lodash#reduce as a way to combine all the grouped properties. lodash#group for grouping each of the mapped attributes, and finally lodash#assign to contain all the properties and their respective groups into one object.

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>


来源:https://stackoverflow.com/questions/46710540/grouping-an-object-with-two-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!