0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is almost the correct answer. I wasn't able to directly access value and label using {item.value} and {item.label} but by using {jsonData[0][item]['value']} instead, I was able to. Why [0] because react was automatically enclosing the JSON object in an array element. I was able to access {item.value} and {item.label} as suggested by you by using Object.values(jsonData[0]).map((item) ... instead of Object.keys(jsonData).... Thanks for your answer. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.