Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  134] [ 5]  / answers: 1 / hits: 15337  / 9 Years ago, fri, october 30, 2015, 12:00:00

Let's say we have this JavaScript object:


var object = {
innerObject:{
deepObject:{
value:'Here am I'
}
}
};

How can we check if value property exists?


I can see only two ways:


First one:


if(object && object.innerObject && object.innerObject.deepObject && object.innerObject.deepObject.value) {
console.log('We found it!');
}

Second one:


if(object.hasOwnProperty('innerObject') && object.innerObject.hasOwnProperty('deepObject') && object.innerObject.deepObject.hasOwnProperty('value')) {
console.log('We found it too!');
}

But is there a way to do a deep check? Let's say, something like:


object['innerObject.deepObject.value']

or


object.hasOwnProperty('innerObject.deepObject.value')

More From » javascript

 Answers
19

There isn't a built-in way for this kind of check, but you can implement it easily. Create a function, pass a string representing the property path, split the path by ., and iterate over this path:




Object.prototype.hasOwnNestedProperty = function(propertyPath) {
if (!propertyPath)
return false;

var properties = propertyPath.split('.');
var obj = this;

for (var i = 0; i < properties.length; i++) {
var prop = properties[i];

if (!obj || !obj.hasOwnProperty(prop)) {
return false;
} else {
obj = obj[prop];
}
}

return true;
};

// Usage:
var obj = {
innerObject: {
deepObject: {
value: 'Here am I'
}
}
}

console.log(obj.hasOwnNestedProperty('innerObject.deepObject.value'));




[#64553] Wednesday, October 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregoriocoya

Total Points: 549
Total Questions: 111
Total Answers: 104

Location: Saint Helena
Member since Mon, Jan 16, 2023
1 Year ago
;