JS: Property Key
Property key
Example. property key of string type
/* property keys of string type */ console.log({ "a": 1, "b": 2 }); // { a: 1, b: 2 }
Omitting string quotation mark
if the key name doesn't contain space or other odd characters, the quotation mark can be omitted. see JS: Dot vs bracket syntax for property access
// property keys of string type // omit the quote in string const jj = { a: 1, b: 2 }; console.log(jj); // { a: 1, b: 2 }
// verify property key without quote is string type console.assert( typeof Object.keys({ a: 1 })[0] === "string", );
Implicit conversion of key to string type
If a key is not symbol or string, it is converted to string implicitly.
// number keys are auto converted to string type console.assert( typeof Object.keys({ 3: 9 })[0] === "string", ); console.assert( typeof Object.keys({ 3.2: 9 })[0] === "string", );
Property key of symbol type
// add a property of symbol key type const xsym = Symbol(); const jj = { [xsym]: 3 }; console.log(jj); // { Symbol(): 3 }
Computed property key
To evaluate a variable as property key, put it inside a square bracket, like this:
obj = {[expr]:value}
// computed key name from a variable const xx = "dog"; const xobj = { [xx]: 3 }; console.log(xobj); // { dog: 3 }