# オブジェクトの代入

今までに登場している物で言えば、連想配列や JSON 形式のデータがオブジェクトと呼ばれる。\
データのひとかたまりをそう呼ぶんだなーと思ってもらえると良いかもしれない。

ちなみに細かいことを言うと、配列もオブジェクトの一種なんだって。

## 基本的な考え方

「キー」と「バリュー」の関係を抑えておこう。

「キー」は表札、「バリュー」は中身。プログラムの例でも `key` と `value` で表現されていることも多かったりする。

## オブジェクトを作る

オブジェクトの代入の基本は `{}` を利用する方法。

```
const example = {
    "key": "value"
};
```

これで、example の `key` という名の下に `value` という文字列が入る。\
キーについてはクォートを省略できるので、

```
const example = {
    key: "value"
};
```

でも同じ事。

複数を入れていきたい場合には、

```
const example = {
    key1: "value1",
    key2: "value2"
};
```

というような感じになる。

ちなみにキーに使えるのは変数と同じ条件の文字列。気をつけてね。

## オブジェクトを参照する

オブジェクトの中身を扱うときには二つの記法がある。

### ドット記法

```
const example = {
    key1: "value1",
    key2: "value2"
};

console.log( example.key2 );
// 出力内容: value2
```

### ブラケット記法

```
const example = {
    key1: "value1",
    key2: "value2"
};

console.log( example["key2"] );
// 出力内容: value2
```

## 変数を使ってみるとどうなるか

一つ例を見て考えてみよう。

```
const name = "お名前";

const example = {
    name: name
};

console.log( example.name );
// 出力内容は...？
```

整理するとこんな処理になる。

1. name に「お名前が入る」
2. オブジェクトを example に代入する
3. オブジェクトの中身は name: name
4. キーは文字列表現として扱われるので name のまま
5. バリューはクォートされていないため変数扱い。つまりは「お名前」

という事で、 `example.name` を出力すると `お名前` が出てくる事になるわけ。

今度は、インデックスに変数を使いたい場合。今回の例ではメリットを感じないかも知れないけど、時によって使える。

```
const index = "key3";

const example = {
    key1: "value1",
    key2: "value2",
    key3: "value3"
};

// どうしたらindexを利用してexampleから値を取り出せるだろうか？
```

答えは至って簡単。ブラケット記法を利用しよう。

```
console.log(example[index]);
// 出力内容: value3
```

変数の中身を添字に利用したいというシーンはよくあるけど、このやり方なら扱えそうだね。

## 複雑なオブジェクト

オブジェクトの中身は階層にすることができる。\
今更だけど配列も二次元・三次元と組んでいくことができる。

```
const staff = {
    yamada: {
        name: "山田さん",
        gender: "male",
        age: 28
    },
    suzuki: {
        name: "鈴木さん",
        gender: "female",
        age: 26
    }
};

console.log( staff.yamada.name );
// 出力内容: 山田さん
```

配列の例だと

```
const example = [
    [ 1, 0 ],
    [ 2, 4 ],
    [ 5, 9 ]
];

console.log( example[2][1] );
// 出力内容: 9
```

こんな感じ。自分で書くことはあまりないと思うけど、受け取るデータがこうなってることはよくあるので憶えておこう。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kent-and-co.gitbook.io/first-step-js/javascript-woiteiku/no/obujikutono.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
