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:
functionkeyPathExists(obj,keypath){
var keys = keypath.split('.'), key, trace = obj;
while (key = keys.shift()){
if (!trace[key]){
returnnull
};
trace = trace[key];
}
returntrue;
}
//usagesvar abcd = {a:{b:{c:{d:1}}}};
keyPathExists(abcd,'a.b.c.d'); //=> 1keyPathExists(abcd,'a.b.c.d.e'); //=> nullif (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:
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"