开发者问题收集

React:如何访问对象中的数组?

2020-03-17
90

有点新手问题,而且今天有点晚了,但是我该如何访问对象中的数组?我得到了 undefined & TypeError: Cannot read property 'length' of undefined 。我可以正常获取对象数据(Id、ElemId 等)。

...
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]); 
}
2个回答

这是因为最初您的查找器对象没有结果数组。尝试一下,看看是否有效。

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]); 
}
Atin Singh
2020-03-17
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.
Sanu Kumar
2020-03-17