如何在 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
廣告