hulkinBrain
hulkinBrain

Reputation: 746

Display nested JSON object with different key-names but same value structure in react-native

I have a nested JSON object in my react-native app which is in the following format, where key names are different but the structure of all values is the same i.e. {"value": "...", "label": "..."}

{
        "name": {
            "value": "Doctor Stranger Things",
            "label": "Name"
        },

        "qualification": {
            "value": "MBBS",
            "label": "Qualification"
        },

        "specialization": {
            "value": "Magic",
            "label": "Specialization"
        }

}

I have tried using .map() but since I'm new to react-native and ES6 I don't have a good grasp on its usage. The following code which I've tried is not working as expected.

render(){
    return(
        <View>
            {jsonData.map((item) => (
                <View>    
                    <Text>{item.value}</Text>
                    <Text>{item.label}</Text>
                </View>
            ))}
        </View>
    );
}

Assuming I have stored the JSON object in a variable jsonData, how do i access value and label of each key without having to access each value like jsonData.name.value or jsonData.qualification.value?

PS: This may seem like a duplicate but I want to avoid using multiple for loops for storage and display purposes. And it's kind of different than what I want.

Upvotes: 0

Views: 999

Answers (1)

Bruno Mazzardo
Bruno Mazzardo

Reputation: 1586

Check Object.keys()

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Try

render(){
    return(
        <View>
            {Object.keys(jsonData).map((item) => (
                <View>    
                    <Text>{item.value}</Text>
                    <Text>{item.label}</Text>
                </View>
            ))}
        </View>
    );
}

more info on Object.keys()

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Upvotes: 1

Related Questions