I am trying to loop through an array of objects in an external json file using the map function. The loop succeeds but I am not sure how to access the object properties. See below.
I am using object.keys(obj).map() but cannot get access to the individual properties. Map keeps outputting the array index numbers.
This is my data I want to iterate through.
[
{
"id" : "12345",
"customer" : "BMW",
},
{
"id" : "45678",
"customer" : "Ford",
},
{
"id" : "78901",
"customer" : "Google",
}
]
I have a state hook that the data will be saved to
const [accountData, setAccountData] = useState('');
The function below gets the data from the external json file and sets the state with it.
axios.get('./data/account-info.json')
.then((response) => {
//set state
setAccountData(response.data);
})
.catch((error) => {
console.log(error);
});
I iterate through the state object with a map function
Object.keys(accountData).map((id,customer) => {
return(
<div>
<p>ID: {id}</p>
<p>Name: {customer}</p>
</div>
)
})
The output keeps printing out the index numbers instead of the appropriate values
//outputted elements
<div>
<p>ID: 0</p>
<p>Name: 0</p>
</div>
<div>
<p>ID: 1</p>
<p>Name: 1</p>
</div>
<div>
<p>ID: 2</p>
<p>Name: 2</p>
</div>
Can you please tell me what I am doing wrong here? I know it has to be something simple.