javascript - 如何检查对象是否具有某些属性
问题描述
我有一个带有一些非常特定键的对象。如何检查另一个对象是否具有完全相同的键?例如:
let myOb = {
name: "somebody",
class: {
number: 9,
section: "C"
},
address: {
house: 22,
street: "Eg street"
PIN: 7893
}
}
if (newOb.containsAll(myOb)) { // this is just a replacement function
// do stuff
}
我想匹配newOb
tomyOb
并查看它们是否具有确切的键。所以,newOb
应该有一个name
, class
, address
; newOb.class
应该有一个number
and section
; newOb.address
应该有house
,street
和PIN
.
我已经知道了hasOwnProperty()
。我想知道如果涉及多个键,是否有更简单的方法来做到这一点。
解决方案
您可以比较两个对象的(递归)键集。
const
myObjA = {
name: "somebody",
class: { number: 9, section: "C" },
address: { house: 22, street: "Eg street", PIN: 7893 }
},
myObjB = {
name: "somebody else",
class: { number: 1, section: "A" },
address: { house: 11, street: "Another st", PIN: 0000 }
};
// Adapted from: https://stackoverflow.com/a/53620876/1762224
const gatherKeys = obj => {
const
isObject = val => typeof val === 'object' && !Array.isArray(val),
addDelimiter = (a, b) => a ? `${a}.${b}` : b,
paths = (obj = {}, head = '') => Object.entries(obj)
.reduce((product, [key, value]) =>
(fullPath => isObject(value)
? product.concat(paths(value, fullPath))
: product.concat(fullPath))
(addDelimiter(head, key)), []);
return new Set(paths(obj));
};
const
diff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item))),
equalByKeys = (a, b) => diff(gatherKeys(a), gatherKeys(b)).size === 0;
console.log(equalByKeys(myObjA, myObjB));
.as-console-wrapper { top: 0; max-height: 100% !important; }
推荐阅读
- node.js - 尝试在 http.put 正文中发送 2+ 个对象,后端返回空正文
- mysql - 使用vb.net备份和恢复数据mysql
- vb.net - 编译器生成的 MemberMemberBinding 和 ListBinding
- json - 出现错误:math/big: cannot unmarshal into a *big.Int
- c# - 为什么 FirebaseAuth.IdTokenChanged 在登录时调用 2 次?
- javascript - 使用 jquery 将 DB 值传递给模态
- java - 没有 Completable.defer 我不知道我的函数在哪里工作
- oracle - Oracle函数在单行中选择多行不起作用
- mysql - 如何使用 Rails 创建此查询?
- gradle - Gradle 构建的战争任务比 build.gradle 中的依赖项添加了额外的 jar