[英]How to merge two almost identical arrays/objects (with underscorejs or similiar libary)?
We got one old list and a new one. 我们得到了一个旧清单和一个新清单。 The Plan is to merge both even if some new key-value-pairs were added.
即使添加了一些新的键值对,该计划也要合并两者。
var oldList = [{
id: 1,
name: 'Michael',
sex: 'male',
goodlooking: 1
}, {
id: 2,
name: 'John',
sex: 'male'
}, {
id: 3,
name: 'Laura',
sex: 'female'
}];
AND... 和...
var newList = [{
id: 1,
name: 'Cindy',
sex: 'female'
}, {
id: 2,
name: 'Herry',
sex: 'male'
}, {
id: 3,
name: 'Laura',
sex: 'female',
goodlooking: 1
}];
Now I am trying to merge these both together and get the most out of both by replacing the values of equal keys. 现在,我尝试将两者合并在一起,并通过替换相等键的值来充分利用两者。 In particular the merged list should look like this:
特别是合并后的列表应如下所示:
var mergedList = [{
id: 1,
name: 'Cindy',
sex: 'female',
goodlooking: 1
}, {
id: 2,
name: 'Herry',
sex: 'male'
}, {
id: 3,
name: 'Laura',
sex: 'female',
goodlooking: 1
}];
Michael changed his name and sex, but stays goodlooking. 迈克尔改变了名字和性别,但保持好看。 John changed his name to Henry and Laura discovered her inner beauty.
约翰(John)改名亨利(Henry),劳拉(Laura)发现了她的内在美。
var mergedList = _.map(oldList, function (oldElem) {
var newElem = _.find(newList, {id: oldElem.id});
return _.merge(oldElem, newElem);
});
A solution in plain Javascript: 用纯Javascript解决方案:
var oldList = [{ id: 1, name: 'Michael', sex: 'male', goodlooking: 1 }, { id: 2, name: 'John', sex: 'male' }, { id: 3, name: 'Laura', sex: 'female' }], newList = [{ id: 1, name: 'Cindy', sex: 'female' }, { id: 2, name: 'Herry', sex: 'male' }, { id: 3, name: 'Laura', sex: 'female', goodlooking: 1 }], theList = JSON.parse(JSON.stringify(oldList)); // make copy newList.forEach(function (a) { theList.some(function (b) { if (a.id === b.id) { Object.keys(a).forEach(function (k) { b[k] = a[k]; }); return true; } }); }); document.write('<pre>' + JSON.stringify(theList, 0, 4) + '</pre>');
Something like this maybe? 像这样的东西?
will override everything from the oldList with values available in the newList and adds new values if they are present. 将使用newList中可用的值覆盖oldList中的所有内容,并添加新值(如果存在)。
mergedList = [];
_.each(oldList, function(listItem, index){
copy = listItem;
newValues = _.findWhere(newList, {"id": listItem.id});
_.each(newValues, function(val,key){
copy[key] = val;
});
mergedList[index] = copy
});
Somethink like this: 像这样:
var a = oldList.length,
mergedList = [];
while(a--){
var oldData = oldList[a];
newKeys = Object.keys(newList[a]);
for (var i=0;i<newKeys.length;i++){
var key = newKeys[i];
oldData[key] = newList[a][key]
}
}
Directly use lodash's merge method. 直接使用lodash的merge方法。
var mergedList = _.merge(oldList, newList);
It recursively merges own enumerable properties. 它递归合并自己的可枚举属性。
https://lodash.com/docs#merge https://lodash.com/docs#merge
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.