2

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]); 
}
1
  • Maybe try let finder = this.state.Finder Commented Mar 17, 2020 at 5:55

2 Answers 2

2

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]); 
}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.