JavaScript:深度检查对象具有相同的键

yzuktlbb  于 2023-06-04  发布在  Java
关注(0)|答案(4)|浏览(503)

问题类似于:How can I check that two objects have the same set of property names?但只有一个区别
我想检查一下:

var objOne = {"a":"one","b":"two","c":{"f":"three_one"}};
var objTwo = {"a":"four","b":"five","c":{"f":"six_one"}};

在所有级别中具有相同的集?
例如,deepCheckObjKeys(objOne, objTwo)将返回true,其中deepCheckObjKeys(objOne, objThree)返回false,如果:

var objThree = {"a":"four","b":"five","c":{"g":"six_one"}};

由于objThree中的objThree.a.c.fundefined
类似这样的函数:
'use strict';

function objectsHaveSameKeys() {
   for (var _len = arguments.length, objects = Array(_len), _key = 0; _key < _len; _key++) {
      objects[_key] = arguments[_key];
   }

   var allKeys = objects.reduce(function (keys, object) {
      return keys.concat(Object.keys(object));
   }, []);
   var union = new Set(allKeys);
   return objects.every(function (object) {
      return union.size === Object.keys(object).length;
   });
}

只检查第一级。

PS:objectsHaveSameKeys()ES6等价:

function objectsHaveSameKeys(...objects):boolean {
   const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
   const union = new Set(allKeys);
   return objects.every(object => union.size === Object.keys(object).length);
}
e3bfsja2

e3bfsja21#

如果属性的值是一个对象,我会做一个递归检查。
这里有个有趣的问题实际上,至少有两个:

  • 如果其中一个“对象”是null,而另一个没有属性,该怎么办?true还是false
  • 如果其中一个对象有{a: null},而另一个对象有{a: 17},会怎么样?true还是false
  • 如果其中一个对象有{a: null},而另一个对象有{a: {}},会怎么样?true还是false

在这个例子中,我把null当作一个没有属性的对象,但是它非常依赖于你的用例。我可以想到至少两种其他方法(null不匹配除了null之外的任何东西,或者null不匹配除了非对象之外的任何东西,即使对象没有自己的属性),并且可能还有其他方法。
见评论:

const deepSameKeys = (o1, o2) => {
    // Both nulls = same
    if (o1 === null && o2 === null) {
        return true;
    }

    // Get the keys of each object
    const o1keys = o1 === null ? new Set() : new Set(Object.keys(o1));
    const o2keys = o2 === null ? new Set() : new Set(Object.keys(o2));
    if (o1keys.size !== o2keys.size) {
        // Different number of own properties = not the same
        return false;
    }

    // Look for differences, recursing as necessary
    for (const key of o1keys) {
        if (!o2keys.has(key)) {
            // Different keys
            return false;
        }
        
        // Get the values and their types
        const v1 = o1[key];
        const v2 = o2[key];
        const t1 = typeof v1;
        const t2 = typeof v2;
        if (t1 === "object") {
            if (t2 === "object" && !deepSameKeys(v1, v2)) {
                return false;
            }
        } else if (t2 === "object") {
            // We know `v1` isn't an object
            return false;
        }
    }

    // No differences found
    return true;
};

// Checking your example
const objOne   = {"a": "one",  "b": "two",  "c": {"f": "three_one"}};
const objTwo   = {"a": "four", "b": "five", "c": {"f": "six_one"}};
const objThree = {"a": "four", "b": "five", "c": {"g": "six_one"}};

console.log("objOne vs. objTwo:         ", deepSameKeys(objOne, objTwo));        // true
console.log("objTwo vs. objThree:       ", deepSameKeys(objTwo, objThree));      // false

// `null` checks
console.log("{a: null} vs. {a: 17}      ", deepSameKeys({a: null}, {a: 17}));    // true
console.log("{a: null} vs. {a: {}}      ", deepSameKeys({a: null}, {a: {}}));    // true -- depending on your use case, you may want this to be false
console.log("{a: null} vs. {a: {x:1}}   ", deepSameKeys({a: null}, {a: {x:1}})); // false

// Differing value type check
console.log("{a: 1} vs. {a: '1'}}       ", deepSameKeys({a: 1}, {a: '1'}));      // true
anauzrmj

anauzrmj2#

我猜你正在寻找[这里]提供的函数的深度检查版本:)(How can I check that two objects have the same set of property names?)。
下面是我的尝试。请注意:

  • 解决方案不检查空值,并且不是防弹的
  • 我还没测试过性能。也许OP或其他任何人都可以这样做,并为社区分享。
  • 我不是JSMaven:)
function objectsHaveSameKeys(...objects) {
  const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), [])
  const union = new Set(allKeys)
  if (union.size === 0) return true
  if (!objects.every((object) => union.size === Object.keys(object).length)) return false

  for (let key of union.keys()) {
    let res = objects.map((o) => (typeof o[key] === 'object' ? o[key] : {}))
    if (!objectsHaveSameKeys(...res)) return false
  }
  return true
}
lvmkulzt

lvmkulzt3#

您可以创建递归函数,该函数将返回所有键并检查它们是否与every()相等。

var objOne = {"a":"one","b":"two","c":{"f":"three_one"}};
var objTwo = {"a":"four","b":"five","c":{"f":"six_one"}};

function checkKeys(obj1, obj2) {

  function inner(obj) {
    var result = []

    function rec(obj, c) {
      Object.keys(obj).forEach(function(e) {
        if (typeof obj[e] == 'object') rec(obj[e], c + e)
        result.push(c + e)
      })
    }
    rec(obj, '')
    return result
  }

  var keys1 = inner(obj1), keys2 = inner(obj2)
  return keys1.every(e => keys2.includes(e) && keys1.length == keys2.length)
}

console.log(checkKeys(objOne, objTwo))
jgwigjjp

jgwigjjp4#

此函数只检查键,并将深入检查,直到找到不匹配的内容。
用TypeScript写的:

function checkSameKeys(obj1: { [key: string]: any }, obj2: { [key: string]: any }) {
if (obj1 === null || !obj2 === null) {
    return false
}

const obj1Keys = Object.keys(obj1)
const obj2Keys = Object.keys(obj2)

if (obj1Keys.length !== obj2Keys.length) {
    return false
}

for (const key of obj1Keys) {
    if (obj1[key] !== null && typeof obj1[key] === 'object') {
        if (!checkSameKeys(obj1[key], obj2[key])) {
            return false
        }
    } else if (!obj2Keys.includes(key)) {
        return false
    }
}

return true

}

相关问题