I know there are several similar questions on Stack Overflow but despite trying multiple methods, I am still stuck.
I am trying to traverse a JSON array of objects with structure like this
{
"categories": [
{
"category_id": "198",
"category": "Appliances",
"seo_name": "appliances",
},
{
"category_id": "184",
"category": "Industrial Appliances",
"seo_name": "industrial-appliances"
},
"params": {
"visible": false,
"sort_order": "asc",
}
}
I want to get the category and seo-name of each object within categories.
This is what I tried:
fetch(url, {
method: "GET",
headers: headers,
})
.then((response) => response.json())
.then((json) => {
for (let i in json) {
console.log(json.categories[i].category);
}
});
The response I get is:
console.log(json.categories[i].category);
^
TypeError: Cannot read properties of undefined (reading 'category')
How do I get the category and seo-name fields for each object within the categories array?
>Solution :
Your loop was pretty close – try using the for..of loop:
const json = {
categories: [
{
category_id: "198",
category: "Appliances",
seo_name: "appliances",
},
{
category_id: "184",
category: "Industrial Appliances",
seo_name: "industrial-appliances",
},
],
params: {
visible: false,
sort_order: "asc",
},
};
for (let category of json.categories) {
console.log(category.category + ', ' + category.seo_name)
}
Alternatively, here’s how you’d do it with a traditional for-loop:
const json = {
categories: [
{
category_id: "198",
category: "Appliances",
seo_name: "appliances",
},
{
category_id: "184",
category: "Industrial Appliances",
seo_name: "industrial-appliances",
},
],
params: {
visible: false,
sort_order: "asc",
},
};
for (let i = 0; i < json.categories.length; i++) {
const category = json.categories[i]
console.log(category.category + ', ' + category.seo_name)
}