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