Skip to content Skip to sidebar Skip to footer

Access Nested Property Of An Object

I have to access property on object: var jsonobj= { 'first': { 'second': 120 } } How to check if second is available or not? jsonobj.hasOwnProperty() returns false

Solution 1:

If you want to check the existence of [the unique path to] a nested property [key], this function may help:

function keyPathExists(obj,keypath){
  var keys = keypath.split('.'), key, trace = obj;
  while (key = keys.shift()){
    if (!trace[key]){
      return null
    };
    trace = trace[key];
  }
  return true;
}

//usages
var abcd = {a:{b:{c:{d:1}}}};
keyPathExists(abcd,'a.b.c.d'); //=> 1
keyPathExists(abcd,'a.b.c.d.e'); //=> null
if (keyPathExists(abcd,'a.b.c.d')){
 abcd.a.b.c.d = 2;
}

Please read @nnnnnns comment, especially the provided link within it carefully.


Solution 2:

To change the value, you can use the "dot" notation - so try: jsonobj.first.second = 100


Solution 3:

var jsonobj= {
              "first": {
                           "second": 120
                        }
           }

alert(jsonobj.first.second);

jsonobj.first.second = 100

alert(jsonobj.first.second);​

Solution 4:

Use typeof:

if(typeof jsonobj.first == 'undefined'){
    jsonobj.first = {};
}
if(typeof jsonobj.first.second == 'undefined'){
    jsonobj.first.second = {};
}    
jsonobj.first.second = 100;

Post a Comment for "Access Nested Property Of An Object"