在使用JSON數(shù)據(jù)時(shí),我們通常需要獲取對(duì)象中每個(gè)數(shù)值。下面介紹幾種方式來(lái)實(shí)現(xiàn)這個(gè)目標(biāo)。
<code class='language-javascript'>// 假設(shè)有一個(gè)JSON對(duì)象 const obj = { "name": "Tom", "age": 18, "address": { "province": "Guangdong", "city": "Shenzhen" }, "scores": [80, 85, 90] };
1. 通過(guò)點(diǎn)號(hào)或中括號(hào)方式獲取對(duì)象屬性值
<code class='language-javascript'>// 通過(guò)點(diǎn)號(hào)獲取 const name = obj.name; const age = obj.age; const province = obj.address.province; const score1 = obj.scores[0]; // 通過(guò)中括號(hào)方式獲取 const name = obj['name']; const age = obj['age']; const province = obj['address']['province']; const score1 = obj['scores'][0];
2. 使用解構(gòu)賦值方式獲取
<code class='language-javascript'>const {name, age, address: {province}, scores: [score1]} = obj;
3. 使用Object.keys()方法獲取所有鍵值
<code class='language-javascript'>const keys = Object.keys(obj); // 輸出 ["name", "age", "address", "scores"] keys.forEach((key) => { const value = obj[key]; console.log(`${key}: ${value}`); });
以上三種方式各有優(yōu)劣,具體選擇應(yīng)根據(jù)實(shí)際業(yè)務(wù)需求而定。