0

I have a javascript object, something like this :

var obj = { simpleName: "some name"  name: { firstName: "anudeep", lastName : "rentala" }, address: { country: "XZ", state:"DF" } }

I also have another object like this :

var foo = { loc = "name.firstName" }

Depending on the foo.loc value, I'd have to access the value in obj object. In this scenario, I'd need to access obj.name.firstname. So, far, I've tried something like this:

  var props = foo.loc.split(".");
    for(var prop in props)
    {
       if (obj.hasOwnProperty(prop))
        {
            alert(obj[prop])
        }
    } 

My problem is, I can now access only the name property of obj object, how do I step into it, like name.firstName, I'm aware that obj[name][firstName] would work, but how do i do this dynamically ? Like extend this to obj["prop1"]["prop2"]["prop3"] . .. .["propn"]

Anudeep Rentala
  • 150
  • 1
  • 6

3 Answers3

2

There are few missing ,, and firstname vs firstName, but if you fix those, then this works great:

var obj = { simpleName: "some name",  name: { firstName: "anudeep", lastName : "rentala" }, address: { country: "XZ", state:"DF" } }
var foo = { loc: "name.firstName" }
var props = foo.loc.split(".");
var output = props.reduce( function(prev,prop) {
  if (prev.hasOwnProperty(prop)) { 
    return prev[prop]
  } else {
   // however you want to handle the error ...
  }
}, obj);
alert(output);
caasjj
  • 1,354
  • 8
  • 11
0

You could fix your code like this:

var props = foo.loc.split(".");
var current = obj;
for(var prop in props)
{
  if (current.hasOwnProperty(prop))
  {
     current = current[prop];
     alert(current )
  }
}

but that probably won't be very useful once you start having more complex "selectors", for example, using arrays ("names[2].firstname").

Amit
  • 45,440
  • 9
  • 78
  • 110
  • Thanks, foo.loc.split("."); was edited way back . But that's not really the problem anyway. extend it to obj["prop1"]["prop2"]["prop3"] . .. .["propn"] is. – Anudeep Rentala Sep 22 '15 at 06:17
0

Here is a function:

var obj = { simpleName: "some name",  name: { firstName: "anudeep", lastName : "rentala" }, address: { country: "XZ", state:"DF" } };
var foo = { loc: "name.firstName" };

var checkObj = function(obj, props) {

    var temp = obj;

    for(var i = 0, len = props.length; i < len; i++) {
        if(temp.hasOwnProperty(props[i])) {
            temp = temp[props[i]];
        }
        else return false;
    }
    return temp;
};

console.log(checkObj(obj, foo.loc.split('.')));
Ty Kroll
  • 1,385
  • 12
  • 27