如何检查两个对象是否具有相同的属性名称集? [英] How can I check that two objects have the same set of property names?

查看:131
本文介绍了如何检查两个对象是否具有相同的属性名称集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的应用程序使用node,mocha和chai。我想测试我的返回结果数据属性与我的模型对象之一是对象类型。 (与柴的实例非常相似)。我只是想确认这两个对象具有相同的属性名称集。 我对这些属性的实际价值并不感兴趣。

I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same "type of object" as one of my model objects. (Very similiar to chai's instanceof). I just want to confirm that the two objects have the same sets of property names. I am specifically not interested in the actual values of the properties.

让我说我的模型人如下。我想检查我的results.data是否具有与预期模型相同的属性。所以在这种情况下,Person有一个firstName和lastName。

Lets say I have the model Person like below. I want to check that my results.data has all the same properties as the expected model does. So in this case, Person which has a firstName and lastName.

所以如果 results.data.lastName results.data.firstName 两者都存在,那么它应该返回true。如果其中任何一个不存在,则应返回false。如果results.data具有任何其他属性(如results.data.surname),那么它将返回false,因为姓氏在Person中不存在。

So if results.data.lastName and results.data.firstName both exist, then it should return true. If either one doesn't exist, it should return false. A bonus would be if results.data has any additional properties like results.data.surname, then it would return false because surname doesn't exist in Person.

模型

function Person(data) {
  var self = this;
  self.firstName = "unknown";
  self.lastName = "unknown";

  if (typeof data != "undefined") {
     self.firstName = data.firstName;
     self.lastName = data.lastName;
  }
}


推荐答案

你可以序列化简单数据以检查是否相等:

You can serialize simple data to check for equality:

data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)

这将给你类似的东西

'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'

作为一个函数......

As a function...

function compare(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);



编辑



如果您正在使用像你说的那样,请查看 http://chaijs.com/api/bdd/#equal-section

如果你只是想检查钥匙......

If you just want to check keys...

function compareKeys(a, b) {
  var aKeys = Object.keys(a).sort();
  var bKeys = Object.keys(b).sort();
  return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}

应该这样做。

这篇关于如何检查两个对象是否具有相同的属性名称集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆