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]
cchamberlain
  • 17,444
  • 7
  • 59
  • 72
awzx
  • 1,023
  • 2
  • 12
  • 31
  • Also [Accessing nested JavaScript objects with string key](http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key). – Amadan Dec 20 '16 at 23:42
  • @Amadan yes there are several good duplicates but they're a pain to find :) – Pointy Dec 20 '16 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 – awzx Dec 20 '16 at 23:51
  • With Lodash: `_.get(tableData[i], 'profile.firstname')` – GG. Dec 20 '16 at 23:55
  • Without lodash: `'profile.firstname'.split('.').reduce((_, x) => _[x], tableData)` =) – cchamberlain Dec 21 '16 at 00:03

1 Answers1

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)
cchamberlain
  • 17,444
  • 7
  • 59
  • 72