Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 중첩된 JSON 객체에 접근하는 방법

JavaScript에서 중첩된 JSON 객체 접근하기

중첩된 JSON 객체에 접근하는 방법은 중첩된 배열에 접근하는 방식과 매우 유사합니다. 여기서 말하는 중첩 객체(nested object)란 또 다른 객체 내부에 포함되어 있는 객체를 의미합니다.

아래 예제에서는 'person'이라는 메인 객체 내부에 'vehicles'라는 객체가 들어 있습니다. 점 표기법(dot notation)을 사용하면 중첩 객체의 속성(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

다음 예제에서는 'airlines'라는 객체가 이중으로 중첩되어 있습니다. 즉, 객체 안의 객체 안에 위치하는 구조입니다. 이처럼 깊이 중첩된 객체의 속성(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.lufthansa);
</script>
</body>
</html>

출력 결과

Mr Ram travels by plane called Air123

대괄호 표기법 활용하기

속성 이름에 공백이 포함되어 있거나 변수를 이용해 동적으로 속성에 접근해야 할 때는 대괄호 표기법(bracket notation)이 더 적합합니다. 예를 들어 위 예제의 'British airways' 속성은 다음과 같이 접근할 수 있습니다.

document.write(person["vehicles"]["airlines"]["British airways"]); // Brt707 출력