如何检查对象是否具有某些属性
How to check if an object has certain properties
我有一个带有一些非常具体的键的对象。如何检查另一个对象是否具有完全相同的键?
例如:
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
与 myOb
匹配,看看它们是否有准确的密钥。所以,newOb
应该有一个name
、class
、address
; newOb.class
应该有一个 number
和 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:
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; }
我有一个带有一些非常具体的键的对象。如何检查另一个对象是否具有完全相同的键? 例如:
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
与 myOb
匹配,看看它们是否有准确的密钥。所以,newOb
应该有一个name
、class
、address
; newOb.class
应该有一个 number
和 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:
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; }