Reputation: 321
I have an object like below:
var car =
{
"bmw":
{
"price": $100000
}
};
I am checking if property-price exists in the object-car:
var checkPropertyExistsInObject = function(obj, property) {
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < args.length; i++) {
if (!obj || !obj.hasOwnProperty(args[i])) {
return false;
}
obj = obj[args[i]];
}
return true;
}
if(checkPropertyExistsInObject(car,'bmw','price')){
return true ;
else
return false;
I am able to check if property-price exists in object-car but I want to check for the property-price 's length(not price's value length) too. I am not able to figure the condition how to do it.
Any help would be appreciated!!!
Upvotes: 1
Views: 130
Reputation: 9592
Object.keys provide all keys of that Object as an array . Check length of the key .
if(checkPropertyExistsInObject(car,'bmw','price')){
// Length of the key
return Object.keys(car['bmw'])[0].length
} else{
return false;
}
Upvotes: 1
Reputation: 5245
You can use Object.keys
to iterate over the keys of an object, like this:
var o = {bmw: {price: 1000}},
keys = Object.keys(o),
length = -1
for (var i = 0; i< keys.length; i++){
var key = keys[i];
if (key == 'bmw'){
length = key.length; // access the length here;
break;
}
}
Upvotes: 2