1

I have an object like this:

var myob= {
title: 'Hey',
list: [3, 74, 25],
myObject: {
  myName: {
   first: "Joe",
   second: "Flynn"
}
}

I am trying to access the inner content via bracket notation.

myob["title"] //works fine, returns 'Hey'
myob["list[0]"] //Doesn't work, returns undefined
myob["myObject[objectTitle]"] //Doesn't work, returns undefined

Why doesn't this work? Is there a way I could do this, preferably still using the same content inside the brackets...?

Link to a jsfiddle: https://jsfiddle.net/j24dxpao/

Ben Gubler
  • 1,393
  • 3
  • 18
  • 32

3 Answers3

4

For these kind of string-based nested object access, you might wanna use a library like lodash's get or equivalent, as it is not natively possible.

const _ = require("lodash")
const schoolEvent = {
    guests: [
        {name: "John", handsome: true},
        {name: "Ben", handsome: false}
    ]
}

_.get(schoolEvent, "guests[0].name") // "John"
Radioreve
  • 3,173
  • 3
  • 19
  • 32
  • Yes, but this is for an npm package and I don't want any dependencies – Ben Gubler Nov 09 '17 at 14:54
  • 2
    If this is the notation you dig, then implement your own get fn. Otherwise, stick with the native notation. As others have pointed out this is the only solution. The only downside is that you have to make sure that each time you go down a level, the key you're on exists. Otherwise, "undefined is not a function" will pop up – Radioreve Nov 09 '17 at 14:56
3

Each index has to be enclosed by it's own brackets.

To access those objects with those paths, use

myob["title"]
myob["list"][0] 
myob["myObject"]["objectTitle"] 
Jesse Schokker
  • 896
  • 7
  • 19
0
var myob= {
title: 'Hey',
list: [3, 74, 25],
myObject: {
  myName: {
   first: "Joe",
   second: "Flynn"
}
}

each key can be accessed by

myob['title']
myob['list'][0]
myob['myObject']['objectTitle']
Pratheesh M
  • 1,028
  • 6
  • 13