Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically access object property using variable

I'm trying to access a property of an object using a dynamic name. Is this possible?

const something = { bar: "Foobar!" }; const foo = 'bar'; something.foo; // The idea is to access something.bar, getting "Foobar!" 
like image 736
RichW Avatar asked Nov 22 '10 11:11

RichW


People also ask

How do you access object properties dynamically?

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] .

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

Can we add dynamically named properties to JavaScript object?

Yes. @thedz: data. PropertyD needs to know the property name, which isn't dynamic enough.

How do I create a dynamic object key?

To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature. The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.


1 Answers

There are two ways to access properties of an object:

  • Dot notation: something.bar
  • Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var something = {   bar: 'foo' }; var foo = 'bar';  // both x = something[foo] and something[foo] = x work as expected console.log(something[foo]); console.log(something.bar)
like image 124
Jan Hančič Avatar answered Oct 07 '22 02:10

Jan Hančič