在数组中查找重复的对象值并合并它们-JAVASCRIPT
我有一个包含某些重复属性的对象数组:以下是数组示例:在数组中查找重复的对象值并合并它们-JAVASCRIPT,javascript,arrays,sorting,duplicates,Javascript,Arrays,Sorting,Duplicates,我有一个包含某些重复属性的对象数组:以下是数组示例: var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}]; 因此,我需要的是合并具有相同x值的对象,如以下数组: var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}] 我喜欢洛达斯图书馆 groupBy(jsonData,'x')产生: 12: [ {x=12,
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
因此,我需要的是合并具有相同x值的对象,如以下数组:
var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]
我喜欢洛达斯图书馆 groupBy(jsonData,'x')产生:
12: [ {x=12, machine1=7}, {x=12, machine2=8} ],
15: [ {x=15, machine2=7} ]
您期望的结果如下所示:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
var groupedByX = _.groupBy(jsonData, 'x');
var result = [];
_.forEach(groupedByX, function(value, key){
var obj = {};
for(var i=0; i<value.length; i++) {
_.defaults(obj, value[i]);
}
result.push(obj);
});
var jsonData=[{x:12,machine1:7},{x:15,machine2:7},{x:12,machine2:8}];
var groupedByX=ux.groupBy(jsonData,'x');
var结果=[];
_.forEach(groupedByX,函数(值,键){
var obj={};
对于(var i=0;i我不确定您是否在寻找纯JavaScript,但如果您是,这里有一个解决方案。嵌套有点繁重,但它完成了任务
// Loop through all objects in the array
for (var i = 0; i < jsonData.length; i++) {
// Loop through all of the objects beyond i
// Don't increment automatically; we will do this later
for (var j = i+1; j < jsonData.length; ) {
// Check if our x values are a match
if (jsonData[i].x == jsonData[j].x) {
// Loop through all of the keys in our matching object
for (var key in jsonData[j]) {
// Ensure the key actually belongs to the object
// This is to avoid any prototype inheritance problems
if (jsonData[j].hasOwnProperty(key)) {
// Copy over the values to the first object
// Note this will overwrite any values if the key already exists!
jsonData[i][key] = jsonData[j][key];
}
}
// After copying the matching object, delete it from the array
// By deleting this object, the "next" object in the array moves back one
// Therefore it will be what j is prior to being incremented
// This is why we don't automatically increment
jsonData.splice(j, 1);
} else {
// If there's no match, increment to the next object to check
j++;
}
}
}
//循环遍历数组中的所有对象
对于(var i=0;i
注意,本示例中没有防御性代码;在传递数据之前,您可能需要添加一些检查以确保数据格式正确
还请记住,您可能必须决定如何处理两个键重叠但不匹配的实例(例如,两个对象都具有machine1
,但一个值为5
,另一个值为9
)。因此,数组中后面出现的任何对象都将优先
const mergeUnique = (list, $M = new Map(), id) => {
list.map(e => $M.has(e[id]) ? $M.set(e[id], { ...e, ...$M.get(e[id]) }) : $M.set(e[id], e));
return Array.from($M.values());
};
在你的情况下,id应该是x
我创建了一个以电子邮件作为标识符的jsperf:
速度要快得多:)嘿,多亏了一吨,这就解决了问题:)目前数据没有同一台机器的两个实例,因此这不应该是一个问题。任何人都可以使用更简单、更短的解决方案?;)