2

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)

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Yup, just tested it myself, it does work ! Thank you good sir, accepting your answer in 10 minutes when allowed by SO
I use this exact pattern in one of my applications to get configuration items: github.com/Canop/miaou/blob/master/libs/Miaou.js#L34
This will be used for a very similar purpose !
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.