Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property via it's keyPath in Javascript?

I have

data = 
{
    'first': {
        'number': 1,
        'text': 'Ya.'
    },
    'second': {
        'number': 10,
        'text': 'Da.'
    }
};

And I really want to access it like:

number = data['first.number'];

Actually in a more flexible way, like:

numberOrText = data[memberName+'.'+propertyName];

Is there any lightweight library, or snippet you can suggest? This is - https://github.com/martinvl/KVCObject - so cool, but a bit overhead for this.

like image 276
Geri Borbás Avatar asked Jul 16 '13 17:07

Geri Borbás


2 Answers

You can easily resolve keypath with reduce function, without using any library.

First, we are creating an example object, called target, with some nested objects inside :

const target = {
    foo: {
        bar: {
            example: 65
        }
    }
};

Then, we define a variable keypath containing keypath string : we want to access example property inside our target object.

const keypath = 'foo.bar.example';    ​

The hard work begins today ! Keypath is splitted by dot separator and we obtain a keys array. We iterate over this array (with reduce function) and for each iteration, we return a new object.

const result = keypath.split('.').reduce((previous, current) => previous[current], target);

Finally, result variable value is 65. It works !

like image 117
Thibault Boursier Avatar answered Oct 01 '22 03:10

Thibault Boursier


With lodash there is a simple method for doing this.

_.get()


enter image description here

like image 41
jose920405 Avatar answered Oct 01 '22 01:10

jose920405