Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเข้าถึง Nested JSON Objects ใน JavaScript

เข้าถึง nested JSON objects เหมือนเข้าถึง nested arrays Nested objects คือ objects ที่อยู่ภายในอีก object

ตัวอย่าง: 'vehicles' เป็น object ภายใน main object 'person' ใช้ dot notation เข้าถึง property (car) ของ nested object

ตัวอย่างที่ 1 - Nested Object ชั้นเดียว

<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 - Doubly Nested Object (ซ้อน 2 ชั้น)

object "air-lines" เป็น doubly nested (อยู่ใน nested object) เข้าถึง property (lufthansa) ด้วย dot notation

<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.lufthansa); 
</script> </body> </html>

ผลลัพธ์

Mr Ram travels by plane called Air123