I have the below JavaScript object.
If myobject
holds the below content, how do I check if a particular key is available or not?
{
"AccountNbr": "1234567890123445",
"AccountName": "Test Bob",
"Address": {
"addressId": 1234,
"line1": "Sample Line 1",
"line2": "Sample Line 2",
"city": "Sample City",
"state": "State"
}
}
For example, to check if key "AccountNbr"
is available. I used the below statement and it returned true.
"AccountNbr" in myobject
and it returned true
. If I have to check if key "addressId"
is available, I used the below statement and it returns false, though the key is available.
"Address.addressId" in myobject
The above statement always returns false
, though addressId
is available. Is there any other alternative to check if addressId
is available?
I also tried giving myobject.Address.addressId
and it always returned false, though the key is available.
2 Answers 2
What you want is:
if('addressId' in myobject.Address){
}
Even better might be:
if('Address' in myObject && 'addressId' in myObject.Address){
}
This is the syntax that in uses, it basically checks if a certain key is among one of the keys in the object referred to in after the word in
.
So you ask if 'aPotentialKey' is one of the Object.keys(myObject)
?
Object.keys(anObject)
will return an array of the keys in an object and if you wanted I guess you could do a for loop through those and check if its equal. But just a nice to know.
Here's a generalized way to do this:
// function for checking whether an object contains a series of properties
function hasMember(object, propertyPath) {
var result = propertyPath.split('.').reduce(function(last, next) {
return {
value: last.value && last.value[next],
hasProperty: last.value && next in last.value
};
}, {
value: object,
hasProperty: true
});
return result.hasProperty;
}
// example scenario
var o = {
"AccountNbr": "1234567890123445",
"AccountName": "Test Bob",
"Address": {
"addressId": 1234,
"line1": "Sample Line 1",
"line2": "Sample Line 2",
"city": "Sample City",
"state": "State"
}
};
console.log(hasMember(o, 'AccountNbr')); // true
console.log(hasMember(o, 'Address.addressId')); // true
console.log(hasMember(o, 'Address.line3')); // false