JSON比较忽略数据/值,只考虑属性/键



比较忽略数据(值(而只考虑键/属性(结构(的两个json对象。我用的是来自lodash的isEqual。这很好。它会忽略钥匙的顺序。我需要的是一种忽略值的方法,只比较两个json的结构。

那是

  1. 删除数据
  2. 比较结构

理想情况下,此比较应返回true。

var _ = require('lodash');
const object1 = {
name: 'Tom',
address: 'USA'
};

const object2 = {
name: 'Kumar',
address: 'India',
};
const comparison = _.isEqual(object1 ,object2)
console.log('Is comparison ?', comparison)

Lodash没有比较键相等的开箱即用函数,但您可以通过比较每个对象中的键的数量来创建一个,如果它们是相同的,则检查它们是否等于组合键的数量(使用Set(:

const isEqualKeys = (a, b) => {
const keysA = Object.keys(a);
const keysB = Object.keys(b);

return keysA.length === keysB.length // has the same length of keys
&& new Set([...keysA, ...keysB]).size === keysA.length // has the same length to the combined keys
};
const o1 = { name: 'Tom', address: 'USA' };
const o2 = { name: 'Kumar', address: 'India' };
const o3 = { name: 'Tom', country: 'USA' };
const o4 = { name: 'Tom', address: 'USA', gender: "f" };
const o5 = { name: 'Kumar' };
console.log(isEqualKeys(o1, o2)); // true
console.log(isEqualKeys(o1, o3)); // false
console.log(isEqualKeys(o1, o4)); // false
console.log(isEqualKeys(o1, o5)); // false

比较嵌套对象的递归解决方案。只有当两个值都是对象时才执行检查,如果其中一个是对象,另一个不是对象,我们将忽略这些值:

const isEqualKeys = (a, b) => {
const keysA = Object.keys(a);
const keysB = Object.keys(b);

const combinedKeys = new Set([...keysA, ...keysB]);

return keysA.length === combinedKeys.size 
&& keysB.length === combinedKeys.size
&& [...combinedKeys].every(key => {
const typeA = typeof(a[key]);
const typeB = typeof(b[key]);

if(typeA === 'object' && typeB === 'object') return isEqualKeys(a[key], b[key]);

return true;
})
};
const o1 = { name: 'Tom', address: 'USA' };
const o2 = { name: 'Kumar', address: 'India' };
const o3 = { name: 'Tom', country: 'USA' };
const o4 = { name: 'Tom', address: 'USA', gender: "f" };
const o5 = { name: 'Kumar' };
const o6 = { name: 'Kumar', b: { c: 5 } };
const o7 = { name: 'Kumar', b: { c: 7 } };
const o8 = { name: 'Kumar', a: 1 };
const o9 = { name: 'Kumar', b: 1 };
const o10 = { name: 'Kumar', b: { d: 7 } };
console.log(isEqualKeys(o1, o2)); // true
console.log(isEqualKeys(o1, o3)); // false
console.log(isEqualKeys(o1, o4)); // false
console.log(isEqualKeys(o1, o5)); // false
console.log(isEqualKeys(o6, o7)); // true
console.log(isEqualKeys(o6, o8)); // false
console.log(isEqualKeys(o6, o9)); // true
console.log(isEqualKeys(o6, o10)); // false

相关内容

  • 没有找到相关文章

最新更新