roshambo
roshambo

Reputation: 2784

React: How to access array in an object?

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]); 
}

Upvotes: 2

Views: 92

Answers (2)

Sanu Kumar
Sanu Kumar

Reputation: 1

You can simply use . operator to access the key of object and use map to traverse the items of array inside the object.

e.g : 
let obj = {
  topic: "accessing array in an object",
  fruits: [
    { name: "banana", price: 30 },
    { name: "apple", price: 50 }
  ]
};

obj.fruits.map(fruit => console.log(fruit.name));

I hope, it helps you.

Upvotes: 0

Atin Singh
Atin Singh

Reputation: 3690

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]); 
}

Upvotes: 2

Related Questions