access values of an object javascript

63 Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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)

2
On

You can use the map function to transform an array:

const myObject = {
"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"
        }
    ]
}
}

const arr = myObject.expansion.contains.map(({display})=>display)
console.log(arr)