0

If know that this should work:

var object = {
  property: "value"
}
var propertyname = "property";
var propertyvalue = object[propertyname];

But how can I get the property value using the propertyname-variable when the object looks like this?

var object = {
  anotherObject: {
    property: "value"
  }
}
var propertyname = "anotherobject.property";
var propertyvalue = object[propertyname]; // This should not work...

Edit: As suggested, in this case the propertyname could be split on ".". But what if it is an arbitrary levels. Could I construct a for-loop somehow that could get the property-value?

EricC
  • 5,720
  • 13
  • 52
  • 71
  • 1
    Split the property name on the `.` character, then repeatedly get the property value using the successive elements. – Barmar Sep 07 '14 at 00:09

1 Answers1

2

The OP's code doesn't work because there is no property with the name anotherObject.property in object. There's a property named anotherObject, and its value is an object with a property named property. To get to this, you have to access these successive levels of properties.

This code splits up the composite property name, and then performs the successive property accesses.

var nameArray = propertyname.split('.');
var propertyvalue = object;
for (var i = 0; i < nameArray.length; i++) {
    propertyvalue = propertyvalue[nameArray[i]];
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This looks exactly what I need. Thanks! Not allowed to accept answer yet though... – EricC Sep 07 '14 at 00:15
  • 1
    Could you please explain exactly why your code works? Why doesn't the OP's work, but yours does? Please see [this meta question](http://meta.stackexchange.com/a/148274/237685). – hichris123 Sep 07 '14 at 00:29