1

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.

Heretic Monkey
12.2k7 gold badges62 silver badges133 bronze badges
asked Oct 26, 2016 at 18:01

2 Answers 2

1

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.

answered Oct 26, 2016 at 18:03
0

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

answered Oct 26, 2016 at 18:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.