-2

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?

hubert_lm
  • 3
  • 1
  • 1
    A simple check what `i` is within the loop would have given you a big clue – charlietfl Jan 09 '22 at 16:31
  • `for (let i in json)` will iterate over the keys in that whole object, so `i` will be `"categories"` and `"params"`, and not a numerical index you expect. You need to iterate over the `json.categories` array, but don't use `for ... in` loop with arrays, use `for ... of` or plain `for` instead. – tromgy Jan 09 '22 at 16:31

1 Answers1

2

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)
}
cbr
  • 12,563
  • 3
  • 38
  • 63