const obj = {
B:0.A: {C:' '.D: {F:' '}}}const attrs = [
'C'.'A.B'.'A.C'.'A.C.D.F'
]
Copy the code
demand
Given the key value string that meets the hierarchical structure, check whether the object has the attribute. For example, ‘A.B.C’ checks whether the object has the attribute A, whether A has the attribute B, and whether B has the attribute C.
hasOwnProperty
HasOwnProperty can be used to determine whether it has an attribute, but this is only for objects with a lower level of hierarchy. Not if you want to judge the properties of deep nodal structures
Implementation approach
For example ‘A.B.C’, check whether A exists in the object first, if so, proceed to the next level, and so on. If there is no A, then there is no need to determine the next level. The important thing to note is that we are only determining the existence of the property, not the value of the property. For example, if C: false, then the result is also true
The implementation code
function keysCheck (obj, attrs) {
try {
attrs.forEach((item) = > {
let objKeys = Object.keys(obj)
let objCopy = obj
const attrItemList = item.split('. ')
for (let y = 0; y < attrItemList.length; y++) {
if (y == attrItemList.length - 1) {
if (objKeys.includes(attrItemList[y])) throw new Error(item)
}
objCopy = objCopy[attrItemList[y]]
if(! objCopy)break
objKeys = Object.keys(objCopy)
}
})
} catch (error) {
return true
}
return false
}
Copy the code