是否可以重新构造以下数组
[
{"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或任何其他库的方法。
答案 0 :(得分:5)
您可以使用reduce()
和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] = 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;
香草ES6:
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;