React: How to access array in an object?

roshambo :

Bit of a rookie question & late in the day, but how do I access an array in an object? I am getting undefined & TypeError: Cannot read property 'length' of undefined. I can get the object data (Id, ElemId, etc) fine.

...
this.state = {
   yfinder: [],
   ...
}

...then api call...
this.setState({
  finder: res.Finder,
  ...
})

JSON:

"Finder": {
    "Id": "23216245567u4",
    "ElemId": "finder",
    "Title": "Your Finder",
    "Description": "This is a description",
    "ResultsTitle": "What program or service are you looking for?",
    "CategoryTitle": "Great! Select a category to continue..",
    "Results": [
       {
         ...
       }
       {
         ...
       }
    ]
}
let finder = this.state.finder;
console.log(finder.Results);

for (var i = 0; i < finder.Results.length; i++) {
  console.log(finder.Results[i]); 
}
Atin Singh :

That's because initially your finder object doesn't have Results array. Try this and see if this works.

let finder = this.state.finder;
console.log(finder.Results);
const resultsLength = finder.Results ? finder.Results.length : null;

for (var i = 0; i < resultsLength; i++) {
  console.log(finder.Results[i]); 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302148&siteId=1