【发布时间】:2017-07-14 03:33:43
【问题描述】:
我是 ReactJS 和 axios 新手。
如果键是数字(如 0、1、2....),我想迭代并提取 json 数据 并且不知道我该如何编写这段代码。 (因为服务器动态提供json,我们不知道它会有多少元素)
现在我可以提取 key = 0 的数据(假设存在这个元素)
class ContentBody extends Component {
constructor(props) {
super(props);
this.state = {
jdata: []
}
}
componentDidMount() {
var self = this;
// read data periodically
setInterval(function() {
axios.get(URL)
.then(function(response) {
self.setState({
jdata: response.data[0].Name
});
})
.catch(function(e) {
console.log("ERROR ", e);
})
}, 1000);
}
}
// below is json data from the server
{
"0": {
"Assigned": false,
"Name": "BebopDrone-Test001.",
"droneID": 0
},
"1": {
"Assigned": false,
"Name": "BebopDrone-B046836",
"droneID": 1
},
"2": {
"Assigned": false,
"Name": "BebopDrone-Test002.",
"droneID": 2
},
"function": "getAllDroneStatus()"
}
// my pseudo code might be
for(int i = 0; i < jsonObject.size(); i++){
if(key is number){
extract corresponding value
}
}
【问题讨论】:
-
请输入一些代码
-
您可以使用
for..in循环在对象中进行迭代。 stackoverflow.com/a/19323734/1619213
标签: javascript json reactjs axios