Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object member exists in nested object

Is there a simpler way than using ___ in object to check the existence of each level of an object to check the existence of a single member?

More concisely: How can I check if someObject.member.member.member.value exists?

like image 878
JustcallmeDrago Avatar asked Jan 13 '11 02:01

JustcallmeDrago


People also ask

How do you check if an object has nested property?

To check if an object has a nested property, use the optional chaining operator - ?. . The ?. operator allows you to read the value of a nested property without throwing an error if the property does not exist on the object, e.g. obj?. a?.

How do you check if an object is inside an object?

The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.

How do I access nested arrays?

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.


2 Answers

In general, you can use if(property in object), but this would be still cumbersome for nested members.

You could write a function:

function test(obj, prop) {     var parts = prop.split('.');     for(var i = 0, l = parts.length; i < l; i++) {         var part = parts[i];         if(obj !== null && typeof obj === "object" && part in obj) {             obj = obj[part];         }         else {             return false;         }     }     return true; }  test(someObject, 'member.member.member.value'); 

DEMO

like image 74
Felix Kling Avatar answered Oct 09 '22 17:10

Felix Kling


You could also try/catch TypeError?

try {   console.log(someObject.member.member.member.value); } catch(e) {   if (e instanceof TypeError) {     console.log("Couldn't access someObject.member.member.member.value");     console.log(someObject);   } } 
like image 33
Oscar Gillespie Avatar answered Oct 09 '22 17:10

Oscar Gillespie