如何在 JavaScript 中訪問巢狀 json 物件?


訪問巢狀json 物件就像訪問巢狀陣列一樣。巢狀物件是位於另一個物件內的物件。

在以下示例中,'vehicles' 是位於名為 'person' 的主物件內的物件。使用點表示法訪問巢狀物件的屬性(car)。

示例-1

線上演示

<html>
<body>
<script>
   var person = {
      "name":"Ram",
      "age":27,
      "vehicles": {
         "car":"limousine",
         "bike":"ktm-duke",
         "plane":"lufthansa"
      }
   }
   document.write("Mr Ram has a car called" + " " + person.vehicles.car);
</script>
</body>
</html>

輸出

Mr Ram has a car called limousine

示例-2

在以下示例中,一個名為“air-lines”的物件雙重巢狀(巢狀在巢狀物件內)。如以下所示,透過點表示法訪問該雙重巢狀物件的屬性(lufthansa)。

線上演示

<html>
<body>
<script>
   var person = {
      "name":"Ram",
      "age":27,
      "vehicles": {
         "car":"limousine",
         "bike":"ktm-duke",
         "airlines":{
            "lufthansa" : "Air123",
             "British airways" : "Brt707"
         }
      }
   }
   document.write("Mr Ram travels by plane called" + " " + person.vehicles.airlines.lufthanza);
</script>
</body>
</html>

輸出

Mr Ram travels by plane called Air123

更新於:2020 年 6 月 29 日

14K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告