Tom
Tom

Reputation: 1457

Is there a one liner in javascript to use an array of string as an object path?

let's say I have the following array :

let path = ['foo','bar']

And I have this item :

let item = {
    faa: 'whatever',
    foo: {
        bar: 'hello there', //general kenobi
        bor: 'nope'
    }
}

I want to access "hello there" using something looking like :

item[path] or item.path or item[path.join(".")]

You get the idea, is this doable and if yes, how ? (of course what is written in this question does not work)

Upvotes: 2

Views: 88

Answers (2)

Hadi Ranjbar
Hadi Ranjbar

Reputation: 1812

You can also use the third party libraries like Lodash.

then you can use Lodash get like this:

import {get} from Lodash

var x=get(item,path.join("."))

The good thing about it is if the item doesn't have 'foo', you won't get an error. It works like safe navigation on an object.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382177

You can do

let target = path.reduce((o, t)=> o ? o[t] : undefined, item)

This one-liner is designed to ensure there won't be any error if there's no match: it just returns undefined.

Demonstration:

let item = {
    faa: 'whatever',
    foo: {
        bar: 'hello there', //general kenobi
        bor: 'nope'
    }
}
let path = ['foo','bar']
let target = path.reduce((o, t)=> o ? o[t] : undefined, item)
console.log(target)

Upvotes: 5

Related Questions