我在这里有两个Json对象:
var obj1=[{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"}]
var obj2=[{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"},{"id":11,"label":"Position"},{"id":12,"label":"Stop Véhicule"}]
我想要的是,合并两个对象与删除两个对象之间的共享值,例如,如果我合并上面的两个对象,我想得到:
[{"id":11,"label":"Position"},{"id":12,"label":"Stop Véhicule"}]
我怎么能用javascript做到这一点?
答案 0 :(得分:0)
您可以执行以下操作: 但是,在这个解决方案中有一些假设,比如对象的键是相同的,顺序也是相同的。
var obj1 = [{ "id": 9, "label": "Tracking haute fréquence" }, { "id": 10, "label": "Output 2" }];
var obj2 = [{ "id": 9, "label": "Tracking haute fréquence" }, { "id": 10, "label": "Output 2" }, { "id": 11, "label": "Position" }, { "id": 12, "label": "Stop Véhicule" }];
function found(obj, i) {
var arrObj = obj1[i];
return JSON.stringify(obj) === JSON.stringify(arrObj) ? true : false;
}
var targetObj = obj2.filter(function (obj, i) {
return found(obj, i) ? false : true;
});
console.log(targetObj);
答案 1 :(得分:0)
您可以通过删除公共对象创建两个已过滤的数组,然后合并它们。
var obj1=[{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"}];
var obj2=[{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"},{"id":11,"label":"Position"},{"id":12,"label":"Stop Véhicule"}];
var filterObj1 = obj1.filter(function(o1) {
return (function() {
return !obj1.filter(function(o2) {
return o2.id === o1.id
}).length
})()
});
var filterObj2 = obj2.filter(function(o1) {
return (function() {
return !obj1.filter(function(o2) {
return o2.id === o1.id
}).length
})()
});
var output = filterObj1.concat(filterObj2);
console.log(output)

答案 2 :(得分:0)
可能的解决方案,使用Array#filter
和Array#map
。
var obj1 = [{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"}],
obj2 = [{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"},{"id":11,"label":"Position"},{"id":12,"label":"Stop Véhicule"}],
hash = obj1.concat(obj2).map(v => v.id),
hash2 = hash.filter(c => hash.indexOf(c) == hash.lastIndexOf(c)),
res = obj1.concat(obj2).filter(v => hash2.indexOf(v.id) > -1);
console.log(res);

答案 3 :(得分:0)
使用reduce
的其他实现。
var obj1=[{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"}];
var obj2=[{"id":9,"label":"Tracking haute fréquence"},{"id":10,"label":"Output 2"},{"id":11,"label":"Position"},{"id":12,"label":"Stop Véhicule"}];
var arr = [...obj1,... obj2];
var nonunique = arr.reduce(function (accumulator,currentValue,currentIndex,array){
if(!accumulator.some(x=>x.id === currentValue.id)){
accumulator.push(currentValue);
}else{
accumulator = accumulator.filter(x =>x.id !== currentValue.id);
}
return accumulator;
},[]);
console.log(nonunique);