我有两个对象,例如:
const objA = {
any: 'string',
some: {
prop: [
{a: 1, b: 2},
{a: 3, b: 4}
],
}
};
const objB = {
some: {
prop: [
{a: 3, b: 4},
{a: 1, b: 2}
],
},
any: 'string'
};
我想拥有一个比较方法,以便在这种情况下的结果是这些对象相等。因此,它需要进行深入的比较,如果发生数组,该方法将比较该数组中的对象,而无视数组中对象的顺序。
我尝试使用Lodash isEqual
函数,但它也检查了数组元素顺序。最好的解决方案是什么?
使用 _.isEqualWith()
const objA = {"any":"string","some":{"prop":[{"a":1,"b":2},{"a":3,"b":4}]}}
const objB = {"some":{"prop":[{"a":3,"b":4},{"a":1,"b":2}]},"any":"string"}
let equal = _.isEqualWith(objA, objB, (a, b) => {
if (Array.isArray(a)) return _(a).xorWith(b, _.isEqual).isEmpty()
})
console.log(equal)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
您可以将对象变成字符串,并按键对对象属性进行排序,而数组则由其内容字符串。
const objHash = obj => {
if(typeof obj !== "object" || obj === null)
return JSON.stringify(obj);
if(Array.isArray(obj))
return "[" + obj.map(objHash).sort().join(",") + "]";
return "{" + Object.entries(obj).sort(([kA], [kB]) => kA.localeCompare(kB)).map(([k, v]) => k + ":" + objHash(v)).join(",") + "}";
}
const objA = {
some: {
prop: [
{a: 1, b: 2},
{a: 3, b: 4}
],
},
any: 'string'
};
const objB = {
some: {
prop: [
{a: 3, b: 4},
{a: 1, b: 2}
],
},
any: 'string'
};
console.log("objA: ", objHash(objA));
console.log("objB: ", objHash(objB));