Search code examples
javascriptecmascript-6iterationdestructure

access values of an object javascript


I am a beginning in javascript. So i have this data with the basic structure like so...

{
"status": "active",
"experimental": false,
"expansion": {
    "extension": [
        {
            "valueBoolean": true
        }
    ],
    "contains": [
        {
            "system": "http://snomed.info/sct",
            "code": "8989938493",
            "display": "Acute"
        },
        {
            "system": "http://snomed.info/sct",
            "code": "889080980089",
            "display": "Chronic"
        },
        {
            "system": "http://snomed.info/sct",
            "code": "889080980089",
            "display": "Fragile"
        }
    ]
}

}

I want to iterate over "contains" and put the values of "display" in an array so i can use it in a react component. I am currently struggling to achieve that. Any help will be appreciated. Thanks in advance.


Solution

  • let res = [];
    const obj = {
    "status": "active",
    "experimental": false,
    "expansion": {
        "extension": [
            {
                "valueBoolean": true
            }
        ],
        "contains": [
            {
                "system": "http://snomed.info/sct",
                "code": "8989938493",
                "display": "Acute"
            },
            {
                "system": "http://snomed.info/sct",
                "code": "889080980089",
                "display": "Chronic"
            },
            {
                "system": "http://snomed.info/sct",
                "code": "889080980089",
                "display": "Fragile"
            }
        ]
    }
    }
    
    obj.expansion.contains.forEach(el => res.push(el.display));
    
    console.log(res)