前段时间做过一个对象部分深度比较的题,题目要求使用JS实现两个对象的部分深度比较方法 comapre,若相等则返回 true,不相等返回 false。compare 的第个参数为原始对象,第二个参数为比较目标对象,只比较目标对象中存在的属性值,若⽬标对象中存在原始对象中不存在的属性,则直接返回 false。下面是一些例子:
简单的比较:
const object = {
id: 1,
name: 'test',
updatedAt: 'now'
};
const objectA = {
name: 'test'
};
const objectB = {
name: 'anotherTest'
};
compare(object, objectA) // return true
compare(object, objectB) // return false
深度比较:
const object = {
id: 1,
name: 'test',
product: {
id: 1,
name: 'product'
},
updatedAt: 'now'
};
const objectA = {
name: 'test',
product: {
name: 'product'
}
};
const objectB = {
name: 'test',
product: {
name: 'anotherProduct'
}
};
compare(object, objectA) // return true
compare(object, objectB) // return false
比较 Array:
const array = [{
id: 1,
name: 'test',
product: {
id: 1,
name: 'product'
},
updatedAt: 'now'
}];
const arrayA = [{
name: 'test',
product: {
name: 'product'
}
}];
const arrayB = [{
name: 'test',
product: {
name: 'anotherProduct'
}
}];
compare(array, arrayA) // return true
compare(array, arrayB) // return false
Object 中嵌套 Array:
const object = {
id: 1,
name: 'test',
products: [{
id: 1,
name: 'product'
}],
updatedAt: 'now'
};
const objectA = {
name: 'test',
products: [{
name: 'product'
}]
};
const objectB = {
name: 'test',
products: [{
name: 'anotherProduct'
}]
};
compare(object, objectA) // return true
compare(object, objectB) // return false
下面是我的实现思路:
先定义一个遍历对象的函数TraversalObject
,将遍历后的每一项存储在一个新的空对象中,并在各项的key中增加该项深度的标识符,例如{a: {id: 1, b: {id: 2, name: 'dog'}}}
转化为{1id: 1, 2id: 2, 2name: 'dog'}
。再定义比较函数compare
,将遍历过的原对象与遍历过的目标对象合并,然后和遍历过的原对象比较,若二者相等,则返回true否则返回false。
function TraversalObject(obj, o = {}, n = 0){
for (let key in obj) {
if (typeof (obj[key]) === "object") {
n++
TraversalObject(obj[key],o,n)
}
else {
o[n + key] = obj[key]
}
}
return o
}
const compare = (a,b) => JSON.stringify(Object.assign({},TraversalObject(a),TraversalObject(b))) === JSON.stringify(TraversalObject(a)) ? console.log('true') : console.log('false');
后来发现这样做有一个问题,就是无法记录外层的key
值,还拿刚才的例子来说,如果原对象是{a: {id: 1, b: {id: 2, name: 'dog'}}}
,目标对象是{a: {id: 1, c: {id: 2, name: 'dog'}}}
的话也会返回true
。所以有没有可以改进的地方,或是更好的方法?