132

Let's say I have a following object:

{ "id": "109",
  "No. of interfaces": "4" }

Following works fine for the "id" key:

alert(obj.id);      // Works fine!

But if keys have spaces, then I cannot access their values using the dot notation e.g.

alert(obj."No. of interfaces");  // Syntax error

How can I access values, whose key names have spaces using the dot notation? Is it even possible with the dot notation? Or do I have to use another way?

Uthman
  • 9,251
  • 18
  • 74
  • 104

2 Answers2

250

The way to do this is via the bracket notation.

var test = {
    "id": "109",
    "No. of interfaces": "4"
}
alert(test["No. of interfaces"]);

For more info read out here:

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 1
    Thank you for referencing the documentation. It is surprising how many answers lack this important detail. – samurai_jane Oct 30 '17 at 10:06
  • 7
    What's difference between the question and answer? – Vishal Kumar Sahu Nov 11 '18 at 23:36
  • 1
    The answer uses bracket notation `test['No. of interfaces']` instead of dot notation `test."No. of interfaces"`. – benjaki Sep 29 '20 at 12:55
  • 1
    How do you accomplish the same thing when doing object deconstructing? `const { Pricing, Location, data[0]["Product 1"] } = data[0]` << doesn't work `const { Pricing, Location, ["Product 1"] } = data[0]` << doesn't work – Vinn Apr 19 '22 at 04:20
12

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!
Laser42
  • 646
  • 2
  • 7
  • 24
  • 1
    -1. No need to list every variation of what kind of expression can replace `test` in Pardeep Jain’s answer, this is just adding noise to the topic. What about `f()["No. of interfaces"]`? What about `((obj)[i])["No. of interfaces"]` ? Etc. – Philippe-André Lorin Jul 01 '22 at 11:14