1

I am trying to store an Object path in to variable. But not works. any one help me please?

here is my try:

var object = {"india": { "chennai" : {"sholing":"hi"}}};

var path = ['india']['chennai']['sholing'];

console.log( object.india.chennai ); //works

console.log( object[path] ); //not works

Live Demo

user2024080
  • 1
  • 14
  • 56
  • 96
  • Why? Further describing your use case would be helpful. – Adam Jenkins May 01 '18 at 17:05
  • 1
    Store an array of strings and use `.reduce()`. You should already know from debugging that your `path` attempt won't be useful. –  May 01 '18 at 17:07
  • You want a [lens](https://medium.com/javascript-inside/an-introduction-into-lenses-in-javascript-e494948d1ea5). – Jared Smith May 01 '18 at 17:07

2 Answers2

2

You'd need to reference each property via bracket notation. So, object[path] won't work (as @Crazy Train pointed out, your debugging should have shown you that your var path = ... throws an error), but if you have an array of paths like let path = ['india', 'chennai', 'sholing'] then you can use them to access the deep property like object[path[0]][path[1]][path[2]].

You're probably much better off using a utility helper to do this for you, such as Lodash's toPath and get functions:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

_.get(object, ['a', '0', 'b', 'c']);
// => 3

_.get(object, 'a.b.c', 'default');
// => 'default'

See other answers:

Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76
2

You could use an array for the keys and a function wich reduces the object by using the keys for the property access.

const getValue = (object, path) => path.reduce((r, k) => (r || {})[k], object);

var object = { india: { chennai: { sholing: "hi" } } },
    path = ['india', 'chennai', 'sholing'];

console.log(object.india.chennai );
console.log(getValue(object, path));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392