在js中,比较两个数组对象中的children对象中的值并将它们的相同元素和不同元素分别提取出来
时间: 2024-02-26 08:59:22 浏览: 61
可以通过循环遍历两个数组对象,递归比较它们的children对象中的值,并将相同元素和不同元素分别存储到新的数组中。具体实现如下:
```javascript
const arr1 = [{id: 1, children: [1, 2, {id: 3, name: 'A'}]}, {id: 2, children: [4, 5, {id: 6, name: 'B'}]}, {id: 3, children: [7, 8, {id: 9, name: 'C'}]}];
const arr2 = [{id: 4, children: [1, 2, {id: 3, name: 'A'}]}, {id: 5, children: [4, 5, {id: 6, name: 'B'}]}, {id: 6, children: [10, 11, {id: 12, name: 'D'}]}];
const sameChildren = [];
const diffChildren = [];
function compareChildren(obj1, obj2) {
if(obj1.children.length !== obj2.children.length) {
diffChildren.push(obj1);
diffChildren.push(obj2);
return;
}
for(let i = 0; i < obj1.children.length; i++) {
const child1 = obj1.children[i];
const child2 = obj2.children[i];
if(typeof child1 === 'object' && typeof child2 === 'object') {
if(child1.id === child2.id && child1.name === child2.name) {
compareChildren(child1, child2);
} else {
diffChildren.push(obj1);
diffChildren.push(obj2);
break;
}
} else if(child1 !== child2) {
diffChildren.push(obj1);
diffChildren.push(obj2);
break;
}
}
if(i === obj1.children.length) {
sameChildren.push(obj1);
sameChildren.push(obj2);
}
}
for(let i = 0; i < arr1.length; i++) {
const obj1 = arr1[i];
for(let j = 0; j < arr2.length; j++) {
const obj2 = arr2[j];
if(obj1.children.length === obj2.children.length) {
compareChildren(obj1, obj2);
}
}
}
console.log("相同元素:", sameChildren);
console.log("不同元素:", diffChildren);
```
这里的思路是,先循环遍历arr1数组中的每个对象,再循环遍历arr2数组中的每个对象,然后通过递归比较它们的children对象中的值。如果相同,则将它们存储在sameChildren数组中,否则存储在diffChildren数组中。最后输出这两个数组即可。需要注意的是,这里对children对象的比较使用了深度比较的方式,因为children对象中的值可能是嵌套的对象。
阅读全文