1

I have a few simple objects defined...

var objectOne = {
    settings: {
        name: "object one"
    }
}

var objectTwo = {
    settings: {
        name: "object two"
    }
}

Now let's pretend I got object from a parameter in the URL - it comes in as a string...

var obj = "objectTwo";

How can I access objectTwo.settings using this obj variable?

I can't do the below because obj is a string:

var settings1 = obj.settings;
var settings2 = [obj].settings; // also doesn't work

I tried stripping the quotes without any luck.

How can I access a top level object using a string?

dmathisen
  • 2,269
  • 3
  • 36
  • 63

3 Answers3

2

window is a neat trick, but could you possibly change your data stricture?

var objects = {
  objectOne: {
    settings: {
        name: "object one"
    }
  },
  objectTwo: {
    settings: {
        name: "object two"
    }
  }
}

var id = "objectOne";
alert(objects[id].settings.name);
Paul Abbott
  • 7,065
  • 3
  • 27
  • 45
1

If it is in the global namespace you could use window[obj].settings.

If not, I don't think there is much you can do except eval as @MikeC mentioned in comments, which is rarely a good idea.

jeffjenx
  • 17,041
  • 6
  • 57
  • 99
1

Good question. Let's invent an Object method to access the object properties dynamically. Object.prototype.getNestedValue() Regardless how deeply your property is located, it takes a series of arguments in order and gets the desired value for you;

In this particular case it's just one argument;

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var objects = {
  objectOne: {
    settings: {
        name: "object one"
    }
  },
  objectTwo: {
    settings: {
        name: "object two"
    }
  }
},
        obj = "objectTwo";
     result = objects.getNestedValue(obj);
console.log(JSON.stringify(result));

You can see getNestedValue() and it's twin setNestedValue() working at here

Community
  • 1
  • 1
Redu
  • 25,060
  • 6
  • 56
  • 76
  • I think you need to make it clearer in your explanation that you've changed the OP's variable definitions to make them properties of a master object. – nnnnnn Jun 16 '16 at 22:37