I have facing a problem with getting data from json object with react. Here is my example data:
const data = [
{
"name": "Adele",
"age": "17",
"exampleValue": "Dummy"
},
{
"name": "Adele",
"age": "17"
}
]
But when i'm trying to get data from the object with "exampleValue". it showing me error.
Is there any way to solve it without adding "exampleValue" in second object?
CodePudding user response:
To read the elements which may present in the node can be read by adding certain condition. Like in your cases you can check if the element in the json node present or not using "hasOwnProperty"
Example
import React, { useState, useEffect, useRef } from "react";
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [arr, setArr] = useState([{
"name": "Adele",
"age": "17",
"exampleValue": "Dummy"
},
{
"name": "Adele",
"age": "17"
},
{
"name": "Adele",
"age": "17",
"exampleValue": "User"
}]);
const renderRow=()=>{
return arr.map((item, index)=>
<div style={{fontSize:18}}>
{item.hasOwnProperty("exampleValue")? item.exampleValue:null}
</div>
)
}
return (
<View style={styles.container}>
{renderRow()}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
Working example: https://snack.expo.dev/L_a4aNEL1