はじめに
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