React组件的概要如下:
const API = 'https://min-api.cryptocompare.com/data/histohour?fsym=BTC&tsym=USD&aggregrate=168&limit=168&api_key=90f934173fe9dd81d5acc53f0a9a6c56a9ffcce322e24e722fa842deeff3601b'
class BtcOverview extends React.Component {
constructor(props) {
super(props);
...
this.intPriceData = [];
}
componentWillMount() {
fetch(API)
.then(results => results.json())
.then(marketData => {
var count = 0;
for (let number in marketData.Data){
this.intPriceData.push(marketData.Data[number].close)
};
})
}当在Fetch()外部访问this.intPriceDash时,它会返回一个对象数组,下面的图片中可以看到其中的一个片段:

我需要一个来自对象数组的标准数组,像这样的1,4,6,但是它不会响应我尝试的任何对象操作符,比如Object.value(),并且总是返回未定义的。
我不知道如何从其中获取所需的值,也不知道数据类型是否有问题。
我不能使用Fetch()方法中的API数据作为标准,因为我使用的代码不容易适应这种情况,因此我尝试在其他地方访问它。
任何想法都会非常感谢。T
发布于 2019-02-01 06:29:50
我不认为这是一个对象数组。它只是开发工具折叠数组的方式,而不是一次显示所有项。
在控制台中运行以下代码片段:let a = []; for(let i = 0; i < 200; i++) a.push(1);
这将生成包含200个元素的数组。然后,看看它将如何在控制台中显示。
发布于 2019-02-01 06:30:22
看起来响应数据已经采用了正确的格式。考虑使用Array#map()方法将其转换为close字段的值数组,该数组存在于marketData.Data数组的每一项上:
const API = 'https://min-api.cryptocompare.com/data/histohour?fsym=BTC&tsym=USD&aggregrate=168&limit=168&api_key=90f934173fe9dd81d5acc53f0a9a6c56a9ffcce322e24e722fa842deeff3601b'
var intPriceData = [];
fetch(API)
.then(results => results.json())
.then(marketData => {
intPriceData = marketData.Data.map(item => item.close);
console.log(intPriceData);
})
更新
考虑到您正在使用ReactJS,下面是一个集成示例,展示了从fetch()返回close数据后如何在组件中呈现该数据
class BtcOverview extends React.Component {
constructor(props) {
super(props);
// Initial state
this.state = { intPriceData : [] };
}
componentWillMount() {
fetch(API)
.then(results => results.json())
.then(marketData => {
// Update state of component
this.setState({
intPriceData : marketData.Data.map(item => item.close)
});
})
}
render() {
return (<ul>{ this.state.intPriceData.map(close => <li>{close}</li>)}</ul>)
}
}发布于 2019-02-01 06:36:02
我认为您只需要对对象数组执行map操作,以便只返回所需的值:
const API = 'https://min-api.cryptocompare.com/data/histohour?fsym=BTC&tsym=USD&aggregrate=168&limit=168&api_key=90f934173fe9dd81d5acc53f0a9a6c56a9ffcce322e24e722fa842deeff3601b'
fetch(API)
.then(results => results.json())
.then(marketData => {
const intPriceData = marketData.Data.map(item => item.close);
console.log(intPriceData);
});
https://stackoverflow.com/questions/54470094
复制相似问题