JSON 資料結構千變萬化,但核心只有物件 `{}`與陣列 `[]`兩種複合型別。掌握四種常見巢狀模式與對應遍歷技巧,能輕鬆應對各類 API 回應。
const arr = [1, 3, 4];
arr[1]; // 3
arr.forEach(v => console.log(v));
const users = [{name: 'Amy', age: 28}, {name: 'Bob', age: 32}];
users[0].name; // 'Amy'
users[0]['age']; // 28
users.forEach(u => console.log(u.name));
const data = {
china: { hangzhou: {item:1}, shanghai: {item:2} },
usa: { ny: {item:1}, la: {item:2} }
};
// 遍歷:for...in 遍歷鍵
for (const country in data) {
console.log(country); // 'china', 'usa'
for (const city in data[country]) {
console.log(' ', city, data[country][city].item);
}
}
// 取值:鍵動態時必須用括號語法
const c = 'china', cy = 'hangzhou';
data[c][cy].item; // 1
const data = {
china: [{name:'hangzhou', item:1}, {name:'shanghai', item:2}],
usa: [{name:'ny', item:1}, {name:'la', item:2}]
};
// 遍歷
for (const country in data) {
console.log(country);
data[country].forEach(city => {
console.log(' ', city.name, city.item);
});
}
// 或轉為扁平陣列處理
const allCities = Object.values(data).flat();
allCities.forEach(c => console.log(c.name));
function walkJson(obj, path = [], callback) {
if (Array.isArray(obj)) {
obj.forEach((v, i) => walkJson(v, [...path, i], callback));
} else if (obj && typeof obj === 'object') {
Object.entries(obj).forEach(([k, v]) => walkJson(v, [...path, k], callback));
} else {
callback(obj, path); // 葉子節點
}
}
// 使用
walkJson(apiResponse, [], (val, path) => {
console.log(path.join('.'), '→', val);
});
// 選項鏈
const item = data?.china?.[0]?.item;
// Lodash get
_.get(data, 'china.0.item', 'default');
// 自寫 getPath
function getPath(obj, path, def) {
return path.split('.').reduce((o, k) => (o && o[k] !== undefined ? o[k] : def), obj);
}
// 模式三
type NestedDict = Record>;
// 模式四
type DictOfArrays = Record>;
// 索引簽名
interface ApiResponse {
[country: string]: Array<{name: string, item: number}>;
}
識別 JSON 結構模式,選對遍歷方式(`for...in` 遍歷物件鍵、`forEach` 遍歷陣列),善用選項鏈與工具函式,能寫出健壯、易讀的資料處理代碼。