<button onclick="testInnerObjectProperty()"> Test inner object property direct access</button>
<button onclick="testInnerObjectPropertyWithIndexerEval()"> Test inner object property access using [path] via eval</button>
<button onclick="testInnerObjectPropertyWithIndexer()"> Test inner object property access using [path]</button>
<button onclick="testInnerObjectPropertyByParsingPath()"> Test inner object property by parsing property path</button>
JavaScript
var complexObject = {
prop0:"prop0 value",
prop1: {
prop1prop1: {
prop1prop2prop3: "prop1prop2prop3 value"
},
prop1prop2:"prop1prop2 Value"
},
prop2:[
{prop2prop1:"prop2[prop2prop1] value"},
{prop2prop2:"prop2[prop2prop2] value"}
]
};
var testInnerObjectProperty = function() {
alert(complexObject.prop0);
alert(complexObject.prop1.prop1prop2);
alert(complexObject.prop2[0].prop2prop1);
};
var testInnerObjectPropertyWithIndexer = function(){
alert(complexObject["prop0"]);
alert(complexObject["prop1.prop1prop2"]);
alert(complexObject["prop2[0].prop2prop1"]);
}
var testInnerObjectPropertyWithIndexerEval = function() {
alert(eval('complexObject.'+'prop0'));
alert(eval('complexObject.'+'prop1.prop1prop2'));
alert(eval('complexObject.'+'prop2[0].prop2prop1'));
}
Object.getValue = function(obj, path) {
path = path.replace(/\[(\w+)\]/g, '.$1'); // convert [] access to property access with number
console.log(path);
path = path.replace(/^\./, ''); // trim leading dot
console.log(path);
var props = path.split('.');
for (var propIndex = 0, noOfProps = props.length; propIndex < noOfProps; ++propIndex) {
var propName = props[propIndex];
if (propName in obj) {
obj = obj[propName];
} else {
return;
}
}
return obj;
}
var testInnerObjectPropertyByParsingPath = function() {
alert('Going to parse prop path');
alert(Object.getValue(complexObject,'prop0'));
debugger;
alert(Object.getValue(complexObject,'prop1.prop1prop2'));
alert(Object.getValue(complexObject,'prop2[0].prop2prop1'));
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.