简体   繁体   中英

Do Javascript objects allow keys that contain spaces?

My Data: I have a an Array of Objects:

var totalsArray = [
  { Applications: 1, Computing Servers: 0, Contracts: 0, Country: "United States" },
  { Applications: 1, Computing Servers: 0, Contracts: 0, Country: "Italy" },
  { Applications: 1, Computing Servers: 0, Contracts: 0, Country: "United States" },
  { Applications: 1, Computing Servers: 0, Contracts: 0, Country: "Spain" }
];

My Code: I then try to extract the keys using the following code:

var objectKeys = d3.keys(totalsArray[0]).filter(function(key) { return key;} );

However, I get an error because of the space in the key named " Computing Servers ".

My question: Is there a way to properly create and keep the "space" in the key name/string?

Thank you for any assistance you can offer.

Yes, a propery name can be any string (all values are coerced to strings before they are used internally).

This can be done using quotes (double or single) around names in literals:

{ Applications: 1, "Computing Servers": 0, .. },

Just as it can be done with using the obj[prop] syntax (where prop is any expression that can be converted to a sensible string value):

obj["Computing Servers"] = 42;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM