Sascha Witte
Sascha Witte

Reputation: 1

Pug.js accessing json keys with spacebar or whitespaces in for each loop

I have a problem accessing json keys with whitespaces or spacebars inside in pug for each loops. Backticks, single and double quotes didn't work for me so I had to fall back to this.

.pug file

for element in aJson
  for value, key in element
    if key == "my key with spaces"
      |  
      =value

Is there any other workaround that is cleaner or did I miss something? I use tabs for indentation in my .pug files. I'm using version 3.0.0 (https://www.npmjs.com/package/pug)

the following does not work:

.pug file

for element in aJson
  |  
  =element.`my key with spaces`
----> syntax error

for element in aJson
  |  
  =element.my key with spaces
-----> "my" not found error

my json file looks like this:

{
  "Element": [
    {
      "my key with spaces": "Value 1",
      "Key2": "Value 2",
      "Key3": "Value 3",
      "Key4": "Value 4",
      "Key5": "Value 5"
    },
  ],
  "Element2": [
    {
      "my key with spaces": "Value 1",
      "Key2": "Value 2",
      "Key3": "Value 3",
      "Key4": "Value 4",
      "Key5": "Value 5"
    },
  ],
  ...

}

Upvotes: 0

Views: 141

Answers (1)

Sascha Witte
Sascha Witte

Reputation: 1

@Sean: Thank you that solves my issue. I was aware that you could use the index functions in pug using =element[0],=element[1],... but didn't know you could also access keys this way. Here is the code that worked for me

for element in aJson
  |  
  =element['my key with spaces']

Upvotes: 0

Related Questions