Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Traversing JSON array of objects

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",
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading