0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptで連想配列を扱う

Posted at

はじめに

Webアプリを作成していて、連想配列(Json)で要素のタグ名(id)と値(value)を受け取る仕様になりました。

連想配列とは

「キー」と「データ」のペアを格納するデータ構造です。
通常の配列が整数(インデックス)で要素にアクセスするのに対し、連想配列では任意の文字列や数値をキーとして使用できるため、データの意味が分かりやすくなります。

連想配列を扱う

以下のコードでKeyとValueでループ出来ます。

1階層の場合

const obj = {
    txtA: 'サンプルA',
    txtB: 'サンプルB'
};
for (const [key, value] of Object.entries(obj)) {
    // keyとvalueを使った処理を書く
    console.log(key + ':' + value);
}

txtA:サンプルA
txtB:サンプルB

複数階層の場合

複数階層の場合
const obj = {
    text: {
        txtA: 'サンプルA',
        txtB: 'サンプルB'
    },
    button: {
        btn1: 'サンプル1',
        btn2: 'サンプル2'
    },
};
function getAllKeys(obj) {
    for (const [key, value] of Object.entries(obj)) {
        if (typeof value === "object" && value !== null) {
            getAllKeys(value);
        } else {
            // keyとvalueを使った処理を書く
            console.log(key, value);
        }
    }
}
getAllKeys(obj);

txtA:サンプルA
txtB:サンプルB
btn1:サンプル1
btn2:サンプル2

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?