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.
You can iterate accountData directly, as it's an array.
Each item will be an object, so you need to destructure as you see below.
(you don't need to but that's was the intention I perceived from your code)
And also you need to add a key to each element, to notify React how to keep track of elements.
// 👇 destrcuture the properties
accountData.map(({ id,customer }) => {
return(
{/* 👇 make sure to add keys here too */}
<div key={id}>
<p>ID: {id}</p>
<p>Name: {customer}</p>
</div>
)
})
-- Reply to the [COMMENT] --
so whenever I remove the object.keys() it throws this error at me TypeError: accountData.map is not a function
Would you double check if response.data is as what you mentioned in the post?
If you run the code below, it will correctly print id & customer array.
let accountData = [
{
"id" : "12345",
"customer" : "BMW",
},
{
"id" : "45678",
"customer" : "Ford",
},
{
"id" : "78901",
"customer" : "Google",
}
]
accountData.map(({id, customer}) => console.log(id, customer))
try this
Object.keys(accountData).map((e) => { return(
ID: {e.id}
Name: {e.customer}
) })If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With