-3

I am fetching data from Yelp Api and I am trying to access nested array but I can not .

function categories (){
    props.RestaurantsData.forEach((element,index) => {
      console.log(element.categories)
    });

I get response like this.

Array [
  Object {
    "alias": "seafood",
    "title": "Seafood",
  },
  Object {
    "alias": "burgers",
    "title": "Burgers",
  },
  Object {
    "alias": "newamerican",
    "title": "American (New)",
 

  },
]

when I try categories.title. I keep getting undefined. How can I access all the titles ?

houcin olmostaf
  • 191
  • 1
  • 12
  • What do you get when you just console.log(element)? Or even console.log(props.RestaurantsData) – Pellay Apr 10 '22 at 23:43

1 Answers1

2
function categories (){
    props.RestaurantsData.forEach((element,index) => {
      var items = element.categories;
                items.forEach((item,index) => {
                    console.log(item.title);
            });
    });
}

Categories is an array in itself with objects, you iterated through restaurantData, but not through categories, so it's a simple thing just loop through the categories for each restaurant;

categories.title implies there's only one title per categories, as a single object, but your return has many items as it's an array, or multiple categories;

If you wanted the first category, you'd want to use your same code but access the first object in the categories array like so: element.categories[0].title; the above example just loops through them all.

Ilan P
  • 1,602
  • 1
  • 8
  • 13