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

时间:2020-03-17 05:50:35

标签: javascript arrays reactjs

一个菜鸟问题,直到今天下午,但是如何访问对象中的数组?我得到<input type="text" id="input" value="test">undefined。我可以很好地获取对象数据(Id,ElemId等)。

TypeError: Cannot read property 'length' of undefined

JSON:

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

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

2 个答案:

答案 0 :(得分:2)

那是因为最初您的查找器对象没有Results数组。尝试一下,看看是否可行。

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

答案 1 :(得分: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.