Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read data from json object in reactjs showing error

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading