【初心者向け】JavaScript dictionaryの代わりにオブジェクトを使う方法

JavaScriptにはdictionary型がないため、オブジェクトやMapを使った辞書的な操作方法を初心者向けに解説。キー・値のペア操作を分かりやすく紹介します。

Learning Next 運営
22 分で読めます

【初心者向け】JavaScript dictionaryの代わりにオブジェクトを使う方法

みなさん、他の言語を学んだことがある方なら疑問に思ったことはありませんか?

「JavaScriptでPythonのdictionaryみたいなものは使えないの?」 「キーと値のペアでデータを管理したいんだけど...」 こんな風に感じている方、きっと多いですよね。

実は、JavaScriptには専用のdictionary型がありません。 でも大丈夫です!オブジェクトやMapを使って同じようなことができるんです。

この記事では、JavaScriptでdictionaryの代わりにオブジェクトを使う方法を初心者向けに分かりやすく解説します。 基本的な操作から実用的な活用例まで、一緒に学んでいきましょう。

JavaScriptになぜdictionary型がないの?

実はオブジェクトが辞書の役割

JavaScriptには、PythonやC#のような専用のdictionary型がありません

簡単に言うと、「JavaScriptのオブジェクトが最初から辞書の機能を持っているから」なんです。 だから、わざわざ別の型を作る必要がなかったというわけですね。

さらに、ES6からはMapという新しい選択肢も追加されました。

JavaScriptで辞書的データを扱う方法

JavaScriptで辞書のようなデータを扱う方法は主に3つあります。

// 1. オブジェクト(最も一般的)
const userObject = {
"name": "田中太郎",
"age": 30,
"email": "tanaka@example.com"
};
// 2. Map(ES6以降)
const userMap = new Map();
userMap.set("name", "田中太郎");
userMap.set("age", 30);
userMap.set("email", "tanaka@example.com");
// 3. 空のオブジェクトから始める
const emptyDict = {};
emptyDict["key1"] = "value1";
emptyDict["key2"] = "value2";
console.log("オブジェクト:", userObject);
console.log("Map:", userMap);
console.log("空から構築:", emptyDict);

この中で、最もよく使われるのがオブジェクトです。 シンプルで分かりやすく、JSONとの相性も抜群なんです。

オブジェクトを使った基本操作を覚えよう

値の設定・取得・削除の基本

辞書の基本操作から始めてみましょう。

// 空の辞書を作成
const dictionary = {};
// 値を設定する方法(2つある)
dictionary["apple"] = "りんご"; // ブラケット記法
dictionary.banana = "バナナ"; // ドット記法
dictionary["orange"] = "オレンジ"; // ブラケット記法(推奨)
console.log("辞書の内容:", dictionary);
// {apple: "りんご", banana: "バナナ", orange: "オレンジ"}

値を設定する方法は2つありますが、ブラケット記法の方がおすすめです。 変数をキーとして使ったり、スペースを含むキーを使ったりできるからです。

// 値を取得してみよう
const appleInJapanese = dictionary["apple"];
const bananaInJapanese = dictionary.banana;
console.log("appleは日本語で:", appleInJapanese); // "りんご"
console.log("bananaは日本語で:", bananaInJapanese); // "バナナ"
// 存在しないキーの場合
const grapeInJapanese = dictionary["grape"];
console.log("grapeは日本語で:", grapeInJapanese); // undefined

存在しないキーにアクセスするとundefinedが返されます。 これを利用して、値があるかどうかを確認できますね。

// 値を更新する
dictionary["apple"] = "青りんご";
console.log("更新後のapple:", dictionary["apple"]); // "青りんご"
// 値を削除する
delete dictionary["banana"];
console.log("banana削除後:", dictionary);
// {apple: "青りんご", orange: "オレンジ"}
// キーが存在するかチェック
const hasApple = "apple" in dictionary;
const hasGrape = "grape" in dictionary;
console.log("appleは存在する:", hasApple); // true
console.log("grapeは存在する:", hasGrape); // false

動的なキーを使ってみよう

変数をキーとして使う方法も覚えておきましょう。

// 動的なキーの使用例
const translations = {};
// 変数をキーとして使用
const englishWord = "cat";
const japaneseWord = "猫";
translations[englishWord] = japaneseWord;
// 複数の翻訳を一気に追加
const words = [
{en: "dog", jp: "犬"},
{en: "bird", jp: "鳥"},
{en: "fish", jp: "魚"}
];
words.forEach(word => {
translations[word.en] = word.jp;
});
console.log("翻訳辞書:", translations);
// {cat: "猫", dog: "犬", bird: "鳥", fish: "魚"}

このように、配列の中身を使って辞書を作ることもできます。 実際のアプリ開発でよく使うパターンですね。

便利な辞書操作関数を作ってみよう

辞書管理のためのヘルパー関数

よく使う操作を関数にまとめておくと便利です。

// 翻訳を追加する関数
function addTranslation(dict, english, japanese) {
dict[english] = japanese;
}
// 翻訳を取得する関数
function getTranslation(dict, english) {
return dict[english] || "翻訳が見つかりません";
}
// 翻訳を削除する関数
function removeTranslation(dict, english) {
if (english in dict) {
delete dict[english];
return true;
}
return false;
}
// 使用例
const translations = {};
addTranslation(translations, "house", "家");
console.log("houseの翻訳:", getTranslation(translations, "house")); // "家"
console.log("存在しない単語:", getTranslation(translations, "car")); // "翻訳が見つかりません"
const removed = removeTranslation(translations, "house");
console.log("house削除成功:", removed); // true

こんな風に関数にしておくと、辞書の操作が分かりやすくなります。

辞書管理クラスを作ってみよう

もっと本格的に辞書を管理したい場合は、クラスを作るのがおすすめです。

// 辞書管理クラス
class Dictionary {
constructor(initialData = {}) {
this.data = { ...initialData };
}
// 値を設定
set(key, value) {
this.data[key] = value;
return this; // チェーンメソッドのため
}
// 値を取得
get(key, defaultValue = null) {
return this.data.hasOwnProperty(key) ? this.data[key] : defaultValue;
}
// キーの存在確認
has(key) {
return this.data.hasOwnProperty(key);
}
// 値を削除
delete(key) {
if (this.has(key)) {
delete this.data[key];
return true;
}
return false;
}
// 全てのキーを取得
keys() {
return Object.keys(this.data);
}
// 全ての値を取得
values() {
return Object.values(this.data);
}
// 辞書のサイズ
size() {
return Object.keys(this.data).length;
}
// 辞書をクリア
clear() {
this.data = {};
return this;
}
}

このクラスを使うと、こんな風に辞書操作ができます。

// 使用例
const colorDict = new Dictionary({
"red": "赤",
"blue": "青",
"green": "緑"
});
console.log("初期状態:", colorDict.data);
// チェーンメソッドで連続操作
colorDict
.set("yellow", "黄")
.set("purple", "紫");
console.log("追加後:", colorDict.data);
// 各種操作
console.log("redの値:", colorDict.get("red")); // "赤"
console.log("pinkの値:", colorDict.get("pink", "不明")); // "不明"
console.log("yellowは存在する:", colorDict.has("yellow")); // true
console.log("全てのキー:", colorDict.keys());
console.log("全ての値:", colorDict.values());
console.log("辞書のサイズ:", colorDict.size());

Mapオブジェクトとの違いを知ろう

Mapの基本的な使い方

ES6で追加されたMapオブジェクトも辞書として使えます。

// Mapを使った辞書操作
const userMap = new Map();
// 値の設定
userMap.set("name", "田中太郎");
userMap.set("age", 30);
userMap.set("email", "tanaka@example.com");
// 任意の型をキーとして使える!
userMap.set(1, "数値キー");
userMap.set(true, "真偽値キー");
userMap.set({id: 1}, "オブジェクトキー");
console.log("Mapのサイズ:", userMap.size); // 6

Mapの大きな特徴は、どんな型でもキーとして使えることです。 オブジェクトの場合、キーは文字列に変換されてしまいますが、Mapなら数値や真偽値もそのまま使えます。

// 値の取得と削除
console.log("名前:", userMap.get("name")); // "田中太郎"
console.log("年齢:", userMap.get("age")); // 30
// キーの存在確認
console.log("emailは存在する:", userMap.has("email")); // true
// 値の削除
userMap.delete("age");
console.log("age削除後のサイズ:", userMap.size); // 5
// 反復処理
console.log("=== Map全体の内容 ===");
userMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});

オブジェクトとMapの使い分け

どちらを使うべきか迷った時の判断基準をまとめました。

オブジェクトが向いている場合

  • シンプルなキー・値のペア操作
  • JSONとの変換が必要
  • コードの可読性を重視したい
  • 初心者にとって分かりやすい

Mapが向いている場合

  • 文字列以外をキーとして使いたい
  • サイズの取得が頻繁
  • キーの追加・削除が頻繁
  • より高度な辞書操作が必要
// オブジェクト向きの例
const config = {
"theme": "dark",
"language": "ja",
"autoSave": true
};
// Map向きの例
const cache = new Map();
cache.set(userObject, "ユーザーデータ");
cache.set(123, "数値データ");
cache.set(Date.now(), "タイムスタンプデータ");

実際のアプリで使える例を見てみよう

多言語対応システム

実際のWebアプリでよく使われる多言語対応システムを作ってみましょう。

// 多言語対応辞書システム
class I18nDictionary {
constructor() {
this.translations = {
"ja": {
"hello": "こんにちは",
"goodbye": "さようなら",
"thank_you": "ありがとうございます",
"welcome": "ようこそ"
},
"en": {
"hello": "Hello",
"goodbye": "Goodbye",
"thank_you": "Thank you",
"welcome": "Welcome"
},
"ko": {
"hello": "안녕하세요",
"goodbye": "안녕히 가세요",
"thank_you": "감사합니다",
"welcome": "환영합니다"
}
};
this.currentLanguage = "ja";
}
// 言語を設定
setLanguage(language) {
if (this.translations[language]) {
this.currentLanguage = language;
return true;
}
return false;
}
// 翻訳を取得
translate(key, language = null) {
const lang = language || this.currentLanguage;
if (this.translations[lang] && this.translations[lang][key]) {
return this.translations[lang][key];
}
// 翻訳が見つからない場合は英語で試す
if (lang !== "en" && this.translations["en"][key]) {
return this.translations["en"][key];
}
return key; // それでも見つからない場合はキーをそのまま返す
}
// 短縮形
t(key, language = null) {
return this.translate(key, language);
}
}

このシステムを使うと、こんな風に多言語対応ができます。

// 使用例
const i18n = new I18nDictionary();
console.log("=== 多言語辞書テスト ===");
console.log("日本語 hello:", i18n.t("hello")); // "こんにちは"
console.log("日本語 welcome:", i18n.t("welcome")); // "ようこそ"
i18n.setLanguage("en");
console.log("英語 hello:", i18n.t("hello")); // "Hello"
console.log("英語 thank_you:", i18n.t("thank_you")); // "Thank you"
i18n.setLanguage("ko");
console.log("韓国語 goodbye:", i18n.t("goodbye")); // "안녕히 가세요"

設定管理システム

アプリの設定を管理するシステムも辞書を使って作れます。

// 設定管理辞書システム
class ConfigManager {
constructor(defaultConfig = {}) {
this.config = { ...defaultConfig };
}
// 設定値を取得(ドット記法に対応)
get(key, defaultValue = null) {
const keys = key.split('.');
let current = this.config;
for (const k of keys) {
if (current && typeof current === 'object' && k in current) {
current = current[k];
} else {
return defaultValue;
}
}
return current;
}
// 設定値を設定(ドット記法に対応)
set(key, value) {
const keys = key.split('.');
const lastKey = keys.pop();
let current = this.config;
for (const k of keys) {
if (!(k in current) || typeof current[k] !== 'object') {
current[k] = {};
}
current = current[k];
}
current[lastKey] = value;
return this;
}
// 設定の存在確認
has(key) {
return this.get(key, Symbol('not-found')) !== Symbol('not-found');
}
// 全設定を取得
getAll() {
return { ...this.config };
}
}

この設定管理システムの使用例です。

// 使用例
const config = new ConfigManager({
"app": {
"name": "My Application",
"version": "1.0.0"
},
"database": {
"host": "localhost",
"port": 3306
},
"features": {
"darkMode": false,
"notifications": true
}
});
console.log("=== 設定管理テスト ===");
// ドット記法で設定を取得
console.log("アプリ名:", config.get("app.name")); // "My Application"
console.log("DB ポート:", config.get("database.port")); // 3306
console.log("ダークモード:", config.get("features.darkMode")); // false
// 設定の変更
config.set("features.darkMode", true);
config.set("app.debug", true);
console.log("変更後のダークモード:", config.get("features.darkMode")); // true
console.log("新規設定:", config.get("app.debug")); // true

まとめ

JavaScriptでは、オブジェクトとMapを使って辞書的な操作を簡単に実現できます。

オブジェクトを使う場合

  • シンプルで分かりやすい
  • JSONとの相性が良い
  • 初心者におすすめ

Mapを使う場合

  • より高度な機能が使える
  • 任意の型をキーにできる
  • サイズの取得が簡単

実用的な活用法

  • 多言語対応システム
  • 設定管理システム
  • キャッシュシステム
  • データの変換・マッピング

どちらを使うかは、プロジェクトの要件に応じて決めればOKです。 まずは基本的なオブジェクト操作から始めて、慣れてきたらMapも試してみてくださいね。

ぜひ今日から、JavaScriptでの辞書的データ操作をマスターしてみませんか?

関連記事