草庐IT

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

coder 2025-03-05 原文

问题类似于: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.a.c.fobjThree 中是 undefined

像这样的函数:

'使用严格';

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);
}

最佳答案

如果属性的值是对象,我会进行递归检查。

这里有一个有趣的问题;实际上,有(至少)两个:

  • 如果其中一个“对象”为 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

关于JavaScript:深度检查对象具有相同的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802259/

有关JavaScript:深度检查对象具有相同的键的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  6. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  7. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  8. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

随机推荐