是否可以在javascript中比较2个对象数组。我的要求是我必须比较2个对象数组,我必须在这两个对象数组之间采用公共对象:
考虑第一个对象数组:
[ { id_0: 356,
name_0: 'xxxxx',
id_1: 33,
name_1: 'yyyyyy',
id_2: 602,
name_2: 'zzzzzzz',
collecteddate: '31/03/2011',
key: 'kkkkkkk',
value: '0.41' },
{ id_0: 356,
name_0: 'xxxxxx',
id_1: 33,
name_1: 'yyyyyy',
id_2: 602,
name_2: 'zzzzzz',
collecteddate: '31/03/2011',
key: 'k1k1k1k1k1',
value: '0.20' },
{ id_0: 356,
name_0: 'xxxxx',
id_1: 33,
name_1: 'yyyyy',
id_2: 602,
name_2: 'zzzzzz',
collecteddate: '31/03/2011',
key: 'k2k2k2k2k2k2k2',
value: '1.30' }}]
我的第二个对象数组:
[ { id_0: 356,
name_0: 'xxxxx',
id_1: 33,
name_1: 'yyyyyy',
id_2: 602,
name_2: 'zzzzzzz',
collecteddate: '31/03/2011',
key: 'kkkkkkk',
value: '0.41' },
{ id_0: 356,
name_0: 'xxxxxx',
id_1: 33,
name_1: 'yyyyyy',
id_2: 602,
name_2: 'zzzzzz',
collecteddate: '31/03/2011',
key: 'k1k1k1k1k1',
value: '0.20' },
{ id_0: 356,
name_0: 'xxxxx',
id_1: 33,
name_1: 'yyyyy',
id_2: 602,
name_2: 'zzzzzz',
collecteddate: '31/03/2011',
key: 'k2k2k2k2k2k2k2',
value: '1.30' }}]
我必须比较上面的2个对象,我必须用上面2的公共条目构建另一个对象。在上面的例子中,每个条目在2个数组中是相同的,所以第三个数组应该包含3个条目。有可能做到这一点。帮助我解决这个问题......提前谢谢....
编辑:
我使用了_(下划线)库来检查2个对象是否相等,如果相等,我将该对象推入新数组..是否是它的好解决方案..
答案 0 :(得分:1)
没有第三个库的解决方案 - 纯javascript
像这样的东西(递归) - 可以优化但不太可读。
var compareAndMerge = function(object1, object2) {
var outputObject = {};
var compareSubObject = function(object1, object2) {
var outputObject = {};
for (var k in object1) {
for (var k2 in object2) {
if (typeof object1[k] === 'object' && typeof object2[k2] === 'object') {
var sameObject = compareSubObject(object1[k], object2[2]);
if (sameObject === false) {
return false;
}
outputObject[k] = object1[k];
} else if (object1[k] === object2[k]) {
outputObject[k] = object1[k];
} else {
return false;
}
}
}
return outputObject;
};
for (var k in object1) {
for (var k2 in object2) {
if (typeof object1[k] !== 'object' && object1[k] === object2[k]) {
outputObject[k] = object1[k];
} else if (typeof object1[k] === 'object') {
var sameObject = compareSubObject(object1[k], object2[k]);
if (sameObject !== false) {
outputObject[k] = sameObject;
}
}
}
}
return outputObject;
};
答案 1 :(得分:1)
注意:此解决方案假定对象的所有值都是字符串或数字。
function getCommonObjects(array1, array2) {
var result = [];
for (var i = 0; i < array1.length; i += 1) {
for (var j = 0; j < array2.length; j += 1) {
if (Object.keys(array1[i]).length === Object.keys(array2[j]).length){
var flag = true;
for (var key in array1[i]) {
if (array1[i][key] !== array2[j][key]) {
flag = false;
break;
}
}
if (flag) {
result.push(array2[j]);
break;
}
}
}
}
return result;
}