Languages

JavaScript - access object which has spaces in the object's key?

0 points
Asked by:
Eshaal-Wilkinson
774

How can I access object property which has spaces in its key/name?

I've tried the following way but didn't work:

var user = {
    name: 'Tom',
    'second name': 'Adam',
    'favorite food': {
        italian: 'spaghetti',
        mexican: 'quesadilla'
    }
};

console.log(user.'second name');
console.log(user.'favorite food'.italian);
1 answer
0 points
Answered by:
Eshaal-Wilkinson
774

For properties with space chacacter in its name use bracket notation property accessor:

user['second name'];

Practical example

// ONLINE-RUNNER:browser;

var user = {
    name: 'Tom',
    'second name': 'Adam',
    'favorite food': {
        italian: 'spaghetti',
        mexican: 'quesadilla'
    },
};

console.log(user['second name']); // 'Adam'
console.log(user['favorite food'].italian); // 'spaghetti'

 

See also

  1. JavaScript - object property access: dot notation vs brackets notation

References

  1. Property accessors - JavaScript | MDN
  2. Working with objects - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join