[英]Is there a way in Lodash to merge duplicates?
This is going to be a really question, but one I cannot figure out for the life of me. 这将是一个真正的问题,但是我无法终生解决。 I am not even sure the correct function I could use. 我什至不确定我可以使用的正确功能。
Consider the following: 考虑以下:
As you can see we have an array of objects, each object has a key (the date) and a value of an array. 如您所见,我们有一个对象数组,每个对象都有一个键(日期)和一个数组值。
As we can see there are two objects with the same date. 如我们所见,有两个对象具有相同的日期。 How can I merge those two objects together such that I have one date (August 10th) with an array of two objects instead of two objects with an array of one object. 如何将这两个对象合并在一起,这样我有一个日期(8月10日)和两个对象的数组,而不是两个对象和一个对象的数组。
I think this would be an array method (something like filter?) with a collection method? 我认为这将是一个带有集合方法的数组方法(类似于filter?)?
I am not sure. 我不确定。 Help? 救命?
//Solution starts here:
var results = [];
var temps = {};
//Iterate through the dates to find uniq keys(date).
_.each(dates, function(date) {
//Store uniq keys(date) and it's value.
_.each(date, function(value, key) {
if (temps.hasOwnProperty(key)) {
temps[key] = temps[key].concat(value);
} else {
temps[key] = value;
}
});
});
//Tranform the object into an array.
_.map(temps, function(value, key) {
var item = {};
item[key] = value;
results.push(item);
});
//results is your answer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.