0

for example:

object = {
  name: "Mike",
  age: 15
}

object.age // returns 15 right?

But I want to pass the 'age' key as a variable name:

object = {
  name: "Mike",
  age: 15
}

const age = 10.toString()

How do I get the result of something like this:

object.`${age}`
Redu
  • 25,060
  • 6
  • 56
  • 76
  • `object[age]`, but `10.toString()` is syntactically invalid, and it's uncertain, why you'd want the string `'10'` to begin with. Don't you want `'age'`? – ASDFGerte Dec 26 '21 at 16:52

4 Answers4

1

Try

object["age"]

or

var propName='age'
object[propName]
Boluc Papuccuoglu
  • 2,318
  • 1
  • 14
  • 24
0

You can simply do this by

object[age]
Gahan Vig
  • 196
  • 2
  • 13
0

Properties can be accessed by either . (dot notation) or via brackets [] that is:

object[key_name]
// where key_name is a variable
object["some_key"] // {"some_key":"value"} or {some_value:"value"}
object[19] // {19:"some_value"}
Soyokaze
  • 157
  • 8
0

You can use object destructuring like;

var object = { name: "Mike"
             , age : 15
             },
    {age}  = object;

console.log(age);
Redu
  • 25,060
  • 6
  • 56
  • 76