LoginSignup
0
1

More than 1 year has passed since last update.

JavaScriptのオブジェクトのキーのクォート有無

Posted at

JavaScriptでオブジェクトは以下のように定義すると思います。

// 例1
const sample = {
  id: 1,
  name: "name"
};

しかしながら、以下のような定義も見るかと思います。

// 例2
const sample = {
  "id": 1,
  "name": "name"
};

例2の定義ではキーをクォート(” or ‘)で囲っているのですが、例1では囲っていません。
恥ずかしながら、これまで何となくで使っていて違いをきちんと意識できていなかったので改めて調べてみました。

結論、例1と例2の違いはオブジェクトかJSONかの違いでした。
オブジェクトの定義においてクォートで囲んでも囲まなくても問題はないのですが、囲まないことが基本ルール(※)となっています。一方でJSONを定義する際はダブルクォートでキーを囲むのがルールになっています。
Ref: https://prettier.io/docs/en/options.html#quote-props

※基本ルールと書いたのは例外があるからで、例えば以下のような場合はクォートで囲むそうです。

const sample = {
  "strange key": "value"
}

Ref: https://google.github.io/styleguide/javascriptguide.xml#Array_and_Object_literals

JSON.stringify()とJSON.parse()を使ってみると違いが如実にわかるかと思います。
※JSON.stringify()はJavaScriptのオブジェクトをJSONに変換する関数で、JSON.parse()はJSONをJavaScriptのオブジェクトに変換する関数です。

const sample = {
  id: 1,
  name: "name"
};

console.log(JSON.stringify(sample));  // {"id": 1, "name": "name"}
console.log(JSON.parse(sample)); // {id: 1, name: "name"}
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1