Adam Matan
Adam Matan

Reputation: 136431

Node.js: Reference an inner property of an object by a variable

My Problem

Consider a nested object:

> { a: { b: { c: 3 } } }
{ a: { b: { c: 3 } } }

Accessing an inner property with a dot notation for fixed values is done using a dot notation:

> x.a.b.c
3

I would like to access an arbitrary property depending on some condition, for example, instead of accessing b I would like to access the property who's name is stored in the SOME_VARIABLE variable:

> x.a.{SOME_VARIABLE}.c
3

What have I tried

My question

How can I refer to an object property dynamically, with a property name defined in a variable?

Upvotes: 0

Views: 348

Answers (2)

Rob Raisch
Rob Raisch

Reputation: 17377

You might also consider using a library like lodash which provides functions to "reach inside" a complex object and return a value, of if the path doesn't exist, a default value.

Example:

const _ = require('lodash')

const target = {
  foo: {
    bar: {
      baz: [1, 2, 3]
    }
  }
}

console.log(_.get(target, 'foo.bar.baz.1')) // ==> 2

console.log(_.get(target, 'foo.3.bar', 'DEFAULT')) // ==> DEFAULT

if (_.has(target, 'foo.bar')) {
  // do something interesting
}

const newKey = 'blorg'

_.put(target, `foo.bar.${newKey}`, 'hello?')

/*
  target is now {
    foo: {
      bar: {
        baz: [1, 2, 3]
      },
      blorg: 'hello?'
    }
  }
*/

Upvotes: 1

Atishay Jain
Atishay Jain

Reputation: 1445

There are multiple ways to access an object one of them being [] instead of dots if a object is var object = { inside : '1' } you can access it like this object['inside']. Remember to pass quotes inside if it's static and if it's dynamic pass the variable

I've added an example below

var a = { b: { c: 1 } };

var d = 'b';

console.log(a[d]['c']);

Upvotes: 1

Related Questions