下划线,嵌套组和生成JSON

时间:2018-04-05 06:40:37

标签: javascript underscore.js underscore.js-templating underscore.string.js

我有一个带有重复项的对象数组,我试图获得一个唯一的列表,其中唯一性由对象属性的子集定义。例如,

当前JSON对象:

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

如何按两个属性分组

最后的结果是

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

如何使用下划线使其独特并生成合并" a"键

2 个答案:

答案 0 :(得分:0)

以下是使用reduceObject.values

的vanilla js解决方案
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;
}  ,{}) );

<强>演示

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

答案 1 :(得分:0)

您可以使用groupByxy上创建复合键。然后,使用map迭代分组数据。

&#13;
&#13;
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);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;