Home > Net >  What's the difference between the two types of declaration of 'keys' in key value pai
What's the difference between the two types of declaration of 'keys' in key value pai

Time:10-31

New to js. I am hardcoding an array of objects in javaScript. the structure of it is something like this

const myArray = [
{id:dummy_String_ID1, name: full_name_with_Spaces1, department:department_withSpaces1},
{id:dummy_String_ID2, name: full_name_with_Spaces2, department:department_withSpaces2},
{id:dummy_String_ID3, name: full_name_with_Spaces3, department:department_withSpaces3}
];

What confuses me is the declaration of these keys( id , name, department), I know the values have to be in inverted quotes. But when shall I use the key fields with inverted quotes (like this "id": "12345", "name": "foo bar", "department": "dept 1" ) and when without them (like this id:"1234", name: "foo bar", dept: "dept 1"). What difference does it make?

CodePudding user response:

A key-value pair can be

identifier: expression

or

string_or_number: expression

or

[expression]: expression

where

  • identifier is a valid variable name or a keyword, like for or if
  • string_or_number is a string literal ("foo" or 'bar') or a number literal (like 123)
  • expression is an arbitrary Javascript expression, which includes, but is not limited to, a literal.

Examples:

foo: "bar"
foo: "bar"[0]   Math.sin(14)
"hi there": "whats up"  
[300 1]: "hello"

Note that this is different from JSON, which only allows string literals as keys.

CodePudding user response:

JSON requires you to double-quote all keys of an object. JavaScript does not require this. There is no difference between the following two literals:

{ prop: 42 }
{ "prop": 42 }

But sometimes you want to use a key with characters that are not valid in a JavaScript identifier (leading digits, hyphens, blanks, quotes, colons, etc.), so you must quote the key to become a string which can be used:

{ "person:age": 42 }
{ `age-in-years`: 42 }
{ '"quoted prop"': 42 }

JavaScript allows double and single quotes as well as backticks. Backticks mark template literals and allow you to interpolate placeholders.

If you need dynamic keys, i.e. the value of the key is computed at runtime, you can surround the key with square brackets:

let name = 'computed somewhere else';
let obj = { [name]: 'fancy' }; // will result in {'computed somewhere else': 'fancy'}
  • Related