Home > Back-end >  Reactjs error reading a Javascript Object Notation
Reactjs error reading a Javascript Object Notation

Time:01-26

I have 2 codes.

1.this giving error:

import userdata from "./data.json";
userdata = userdata.userdata;
userdata.map() // do map here.

that giving error: Uncaught TypeError: Cannot read properties of undefined (reading 'userdata')

  1. this works:
import userdata from "./data.json";
userdata.userdata.map() // do map here.

json: {"userdata":[{name, job}, {name, job}]}

why the second code is working?

CodePudding user response:

In the first example you import userdata and then try to assign it the value of userdata.userdata.

This isn't possible as you can't assign a new value to an import.

Therefore when you try map over userdata it is still trying to map over userdata from the initial import (and not userdata.userdata).

If you want this to work rather use a new variable name like below:

import userdata from "./data.json";

const userDataArray=userdata.userdata;
userDataArray.map()

In the second example, you reference the array correctly (with userdata.userdata), instead of trying to assign a value to the import.

  •  Tags:  
  • Related