Access inner object property

by Joy George Kunjikkuru

HTML

<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'));
}