Underscore, Nested Group By and Generate a JSON

2019-08-18 06:57发布

问题:

I have an array of objects with duplicates and I'm trying to get a unique listing, where uniqueness is defined by a subset of the properties of the object. For example,

Current JSON Object:

[{"x":6811,"y":15551,"a":"a"},
{"x":6811,"y":15551,"a":"b"},
{"x":6811,"y":15551,"a":"c"},
{"x":6811,"y":15552,"a":"c"},
{"x":6812,"y":15551,"a":"c"}]

How to group by two property

The last result is

[{"x":6811,"y":15551,"a":["a","b","c"]},
{"x":6811,"y":15552,"a":["c"]},
{"x":6812,"y":15551,"a":["c"]}]

How to use underscore to make it unique and generate a merge "a" Key

回答1:

You can use groupBy to create a composite key on x and y. Then, use map to iterate through the grouped data.

var data = [{"x":6811,"y":15551,"a":"a"},{"x":6811,"y":15551,"a":"b"},{"x":6811,"y":15551,"a":"c"},{"x":6811,"y":15552,"a":"c"},{"x":6812,"y":15551,"a":"c"}]
var groups = _.groupBy(data, ({x,y}) => `${x}_${y}`);
var result = _.map(groups, o => ({...o[0], a : _.pluck(o,'a')}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>



回答2:

Here is a vanilla js solution using reduce and Object.values

var output = Object.values( arr.reduce( (acc, c) => {
  var {x,y} = c; 
  var key = JSON.stringify({x,y}); //create a key with both x and y
  if ( acc[ key ] ) 
  {
    acc[ key ].a.push(c.a); //if key is already set, then push the value in a
  }
  else
  {
     acc[ key ] = c; //else set c as value for this key
     acc[ key ].a = [acc[ key ].a];
  }
  return acc;
}  ,{}) );

Demo

var arr = [{
    "x": 6811,
    "y": 15551,
    "a": "a"
  },
  {
    "x": 6811,
    "y": 15551,
    "a": "b"
  },
  {
    "x": 6811,
    "y": 15551,
    "a": "c"
  },
  {
    "x": 6811,
    "y": 15552,
    "a": "c"
  },
  {
    "x": 6812,
    "y": 15551,
    "a": "c"
  }
];

var output = Object.values(arr.reduce((acc, c) => {
  var {
    x,
    y
  } = c;
  var key = JSON.stringify({
    x,
    y
  }); //create a key with both x and y
  if (acc[key]) {
    acc[key].a.push(c.a); //if key is already set, then push the value in a
  } else {
    acc[key] = c; //else set c as value for this key
    acc[key].a = [acc[key].a];
  }
  return acc;
}, {}));

console.log( output );