使用Underscore重新构造对象数组

时间:2016-09-27 10:55:39

标签: javascript jquery underscore.js

是否可以重新构造以下数组

[
    {"period":"2016-09-18","mp-demo-1":30},
    {"period":"2016-09-18","MP7":20},
    {"period":"2016-09-19","mp-demo-1":13},
    {"period":"2016-09-19","MP7":33},
    {"period":"2016-09-20","mp-demo-1":39},
    {"period":"2016-09-20","MP7":29}
]

进入

[
    {"period":"2016-09-18","mp-demo-1":30,"MP7":20},
    {"period":"2016-09-19","mp-demo-1":13,"MP7":33},
    {"period":"2016-09-20","mp-demo-1":39,"MP7":29},
]

我基本上需要的是通过键(句点)删除重复的条目,并将包含在这些对象中的值添加到单个对象中。

使用underscore.js可以实现吗?或者是否有另一种使用jQuery或任何其他库的方法。

2 个答案:

答案 0 :(得分:5)

您可以使用reduce()Object.assign()

的纯javascript执行此操作

var data = [
  {"period":"2016-09-18","mp-demo-1":30},
  {"period":"2016-09-18","MP7":20},
  {"period":"2016-09-19","mp-demo-1":13},
  {"period":"2016-09-19","MP7":33},
  {"period":"2016-09-20","mp-demo-1":39},
  {"period":"2016-09-20","MP7":29}
];

var obj = {}
var result = data.reduce(function(r, o) {
  if (!obj[o.period]) {
    obj[o.period] = o;
    r.push(obj[o.period]);
  } else {
    Object.assign(obj[o.period], o);
  }
  return r;
}, []);

console.log(result)

要保留原始数据,您可以使用Object.assign()

创建对象的克隆

var data = [
  {"period":"2016-09-18","mp-demo-1":30},
  {"period":"2016-09-18","MP7":20},
  {"period":"2016-09-19","mp-demo-1":13},
  {"period":"2016-09-19","MP7":33},
  {"period":"2016-09-20","mp-demo-1":39},
  {"period":"2016-09-20","MP7":29}
];

var obj = {}
var result = data.reduce(function(r, o) {
  if (!obj[o.period]) {
    obj[o.period] = Object.assign({}, o);
    r.push(obj[o.period]);
  } else {
    Object.assign(obj[o.period], o);
  }
  return r;
}, []);

console.log(result);
console.log(data);

答案 1 :(得分:2)

用lodash:



data = [
    {"period":"2016-09-18","mp-demo-1":30},
    {"period":"2016-09-18","MP7":20},
    {"period":"2016-09-19","mp-demo-1":13},
    {"period":"2016-09-19","MP7":33},
    {"period":"2016-09-20","mp-demo-1":39},
    {"period":"2016-09-20","MP7":29}
];


res = _(data)
    .groupBy('period')
    .map(_.spread(_.merge))
    .value();

console.log(res)

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

香草ES6:

&#13;
&#13;
data = [
    {"period":"2016-09-18","mp-demo-1":30},
    {"period":"2016-09-18","MP7":20},
    {"period":"2016-09-19","mp-demo-1":13},
    {"period":"2016-09-19","MP7":33},
    {"period":"2016-09-20","mp-demo-1":39},
    {"period":"2016-09-20","MP7":29}
];

let map = new Map();

data.forEach(x => map.set(x.period,
    Object.assign(
        map.get(x.period) || {},
        x
)));

console.log([...map.values()])
&#13;
&#13;
&#13;