2

I'm trying to access properties of a JavaScript object by passing a path (string or otherwise):

// In a loop
tableData[i].profile.firstname

where 'profile.firstname' is the path.

Is there a way to access a nested property based on a path in this way?

let firstnamePath = 'profile.firstname'
let firstname     = tableData[i][firstnamePath]
5
  • Also Accessing nested JavaScript objects with string key. Commented Dec 20, 2016 at 23:42
  • @Amadan yes there are several good duplicates but they're a pain to find :) Commented Dec 20, 2016 at 23:43
  • 1
    They are quite similar, but IMO not duplicates, the answer below is quite different and is what I was looking for, because I can use complex paths with such a functional approach Commented Dec 20, 2016 at 23:51
  • With Lodash: _.get(tableData[i], 'profile.firstname') Commented Dec 20, 2016 at 23:55
  • Without lodash: 'profile.firstname'.split('.').reduce((_, x) => _[x], tableData) =) Commented Dec 21, 2016 at 0:03

1 Answer 1

1

Yes, but not with the syntax you've proposed. This is easiest done when your path is an array of strings:

const tableData = (
  { profile: { firstname: 'jim', lastname: 'johnson' }
  }
)
                                                                    
const path = [ 'profile', 'firstname' ]

const valueAtPath = path.reduce((_, x) => _[x], tableData)

console.info(valueAtPath)

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

2 Comments

I'll try this right now
This solution works nicely !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.