137

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?

3
  • 3
    this question is a mistake, it works with the brackets Commented Jun 14, 2018 at 13:43
  • 3
    Note that There's no such thing as a "JSON Object". What you have there is just a plain object. Commented Jan 4, 2019 at 1:50
  • Thanks @MartijnScheffer. Modified the question's language to make the intention more clear. Commented Sep 2, 2023 at 18:58

2 Answers 2

259

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:

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for referencing the documentation. It is surprising how many answers lack this important detail.
What's difference between the question and answer?
The answer uses bracket notation test['No. of interfaces'] instead of dot notation test."No. of interfaces".
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
You are confusing deconstructing with object destructuring. Using OPs example data it would be done like this: const { id, "No. of interfaces": numberOfInterfaces } = test; Note how we must assign it a new variable name inline.
11

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! 

1 Comment

-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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.