Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get javascript object property via key name in variable [duplicate]

Tags:

javascript

Say I have something that looks like this in javascripts:

var obj = {
  subObj : {}
};
var type = 'subObj';

How can I get obj's subObj w/ type? For instance I would like to do something like:

obj.(type);
like image 956
Kyle Decot Avatar asked Dec 19 '11 02:12

Kyle Decot


People also ask

How do you dynamically access object properties?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

Does JavaScript object allow for duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do you find the value of an object in a variable?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!


2 Answers

obj[type]

You use subscript notation.

11.2.1 Property Accessors

Properties are accessed by name, using either the dot notation:

MemberExpression . IdentifierName
CallExpression . IdentifierName

or the bracket notation:

MemberExpression [ Expression ]
CallExpression [ Expression ]
like image 108
Raynos Avatar answered Oct 10 '22 11:10

Raynos


You can treat objects like associative arrays in JavaScript, so you'll be able to access the inner object like:

var obj = {
    subObj : {}
};

var type = "subObj";
var subObj = obj[type];
like image 44
Jon Newmuis Avatar answered Oct 10 '22 11:10

Jon Newmuis