160

I have a JavaScript object that looks something like this:

var myTextOptions = {
  'cartoon': {
     comic: 'Calvin & Hobbes',
     published: '1993'
  },
  'character names': {
    kid: 'Calvin',
    tiger: 'Hobbes'
  }
}

I can access the properties of cartoon easily using myTextOptions.cartoon.comic or whatever. However, I haven't been able to get the syntax right for accessing kid. I've tried the following with no luck:

myTextOptions.character names.kid
myTextOptions."character names".kid
myTextOptions.character\ names.kid
myTextOptions.'character names'.kid
myTextOptions.["character names"].kid
myTextOptions.character%20names.kid
Ed The ''Pro''
  • 875
  • 10
  • 22
julio
  • 6,630
  • 15
  • 60
  • 82
  • more... When I type myTextOptions.character%20n.kid returns 'NaN'. The last property name (kid) doen't matter, should be any other. I'm using FireFox Quantum 8.3.0esr (64-bits) on Debian 9 – Daniel Bandeira May 27 '20 at 13:09
  • In Google Chrome, if you go to inspect element and then hover over the json file data sets, each individual data set will have a tooltip appear showing it's path and it also gives you the option to copy the path into your clipboard. Just an FYI. – Simon Suh Jul 15 '19 at 13:29

4 Answers4

299

Use ECMAscripts "bracket notation":

myTextOptions[ 'character names' ].kid;

You can use that notation either way, reading & writting.

For more information read out here:

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • 4
    julio mentions in the OP that he'd already tried using `myTextOptions.["character names"].kid` - for completeness to this question, I was wondering why that didn't work? – James_F Feb 06 '17 at 09:52
  • 10
    @James_F Because he also used the `dot notation` simultaneously. There must only be one accessor directive. – jAndy Feb 07 '17 at 01:06
  • 2
    oh, yes, sorry - was looking so hard I didn't see the extra dot before the bracket! - thanks – James_F Feb 07 '17 at 09:15
  • Does somebody know if it is a good or bad practice use spaces in object keys? – Juan P. Ortiz Mar 19 '19 at 07:07
  • 2
    @JuanP.Ortiz, This is not a good practice if you are using typescript, you will lose typescript compile check. – Rosdi Kasim Mar 25 '19 at 08:21
  • 1
    @RosdiKasim -- to add, one can use [key: type]: any in typescript. i.e. original key "My Id" which is a string so, can declare "[My_Id: string]: any" in interface; – Pramod Mali Mar 02 '20 at 09:53
7

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;

For more, read on at Working with JS Objects.

So in your case it's myTextOptions['character names'].kid;

Ahmad Awais
  • 33,440
  • 5
  • 74
  • 56
5

We can also do this by -

myTextOptions[ 'character names' ]['kid'];

This is useful when we have consecutive keys which consist of space.

Shubham AK
  • 51
  • 1
  • 2
3

Let me share my solution here I am using VueJs with type script.

I got following json to parse and display in UI

 {
    "Brand": "MAMA",
    "Variety": "Instant Noodles Coconut Milk Flavour",
    "Style": "Pack",
    "Country": "Myanmar",
    "Stars": 5,
    "Top Ten": "2016 #10"
  },

I have created the following model interfere in Typescript

export interface Resto {
    Brand: string;
    Variety: string;
    Style: string;
    Country: string;
    Stars: any;
    Top_Ten: string;
    }

I have called the API as:

   public async getListOfRestos() {
    return (await fetch(
      `http://starlord.hackerearth.com/TopRamen`,
      {
        method: "get",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
        },
        body: undefined
      }
    )) as IFetchResponse<Resto[]>;
  } 

Used in JSX like:

 <div class="parent" v-for="(x,i) in listOfRestos" :key="i">
      <div>{{x.Brand}}</div>
      <div>{{x.Variety}}</div>
      <div>{{x.Style}}</div>
      <div>{{x.Country}}</div>
      <div>{{x.Stars}}</div>
      <div>{{x['Top Ten']}}</div>
  </div>

Same can also work in React and Angular.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Vikas Gupta
  • 1,293
  • 1
  • 15
  • 21