我想在p5.js中迭代这些数据
var ms = []
function preload() {
var url ='https://dest/url'
ms = loadJSON(url)
}
我希望返回一个数组,但它似乎没有任何明智的回报。
但是,如果我将相同的数据粘贴到Javascript控制台,我会得到不同的数据:
如何迭代这些数据(它不作为数组加载)或将其转换为数组?
答案 0 :(得分:4)
我认为你的意思是:
var array;
for (var key in ms) {
if (!array) {
array = [a[key]];
} else {
array.push(a[key]);
}
}
console.log(array); // [ {'time': .... }, {...}, .. ]
答案 1 :(得分:1)
您正在获取一系列对象,以及如何简单地迭代它们
var data = [{"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"} ];
for(obj of data){
console.log("time and rate: ", obj.time, obj.rate)
}

答案 2 :(得分:0)
正如其他人在评论中指出的那样,你所拥有的本质上是一个数组或类似数组的对象更加精确,这些可以很容易地转换为正确的数组,如下所示:
ms.length = Object.keys(ms).length;
var msArray = Array.prototype.slice.call(ms);
答案 3 :(得分:0)
jettpleyn是唯一在P5中有效的答案。
最终 - 我突然意识到,通过将服务器返回的JSON更改为包含数组而不是数组的对象,我可以让生活更轻松
{ "data":
[{"time":"85579.54189181328","rate":177.66287},{"time":"81978.61475682259","rate":177.66287},{"time":"78377.54175782204","rate":177.66287},{"time":"74776.58741879463","rate":177.66287},{"time":"71175.57481980324","rate":177.66287},{"time":"67574.59330582619","rate":177.66287},{"time":"63973.427922964096","rate":177.66287},{"time":"60372.39295697212","rate":177.66287},{"time":"56771.37366294861","rate":177.66287},{"time":"53170.276379823685","rate":177.66287},{"time":"49569.180530786514","rate":177.66287},{"time":"45968.02240085602","rate":177.66287},{"time":"42365.825628995895","rate":177.66287},{"time":"38764.64792180061","rate":177.71416},{"time":"35163.241872787476","rate":177.71416},{"time":"31562.00651884079","rate":177.72556},{"time":"27960.898827791214","rate":177.73126},{"time":"24359.687824964523","rate":177.67998},{"time":"20758.03328180313","rate":177.67998},{"time":"17156.808887004852","rate":174.53839},{"time":"13555.605601787567","rate":174.9276},{"time":"9954.546007871628","rate":175.35431},{"time":"6353.40945982933","rate":175.96582},{"time":"2752.3464789390564","rate":175.84541}]
}