javascript 迭代p5.js中的JSON数组

yc0p9oo0  于 2023-02-11  发布在  Java
关注(0)|答案(5)|浏览(128)

我的服务器返回:

我想在p5.js中迭代这些数据

var ms = []

function preload() {
  var url ='https://dest/url'
  ms = loadJSON(url)
}

我期望它返回一个数组,但它似乎没有返回任何有意义的东西。

但是,如果我将相同的数据粘贴到Javascript控制台,我会得到不同的数据:

我如何迭代这个数据(它不是作为数组加载的)或将它转换成数组?

3htmauhk

3htmauhk1#

我想你是这个意思:

var array;
for (var key in ms) {
   if (!array) {
      array = [a[key]];
   } else {
      array.push(a[key]);
   }
}
console.log(array); // [ {'time': .... }, {...}, .. ]
ntjbwcob

ntjbwcob2#

你得到了一个对象数组,下面是你如何简单地迭代它们

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)
}
qkf9rpyu

qkf9rpyu3#

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}]
}
fquxozlt

fquxozlt4#

正如其他人在评论中指出的那样,你所拥有的本质上是一个数组或类似数组的对象,更准确地说,它们可以很容易地转换成一个合适的数组,如下所示:

ms.length = Object.keys(ms).length;
var msArray = Array.prototype.slice.call(ms);
jgzswidk

jgzswidk5#

在p5.jsgithub中有一个关于这个问题的问题,不止一个人建议使用Object.values(ms)将对象转换为数组。
必须在预加载功能之后进行。

相关问题