You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将async/await获取的JSON对象转换为指定格式的数组?

解决方案

需求1:生成长度为1的数组,元素为拼接的键值对字符串

如果你需要的是类似 ['name:iss, lat:45.123, lng:12.456'] 这样的结果,可以用 Object.entries() 遍历对象的键值对,拼接成目标字符串后放入数组:

const apiurl = 'https://api.wheretheiss.at/v1/satellites/25544';

async function getArray(){
  const response = await fetch(apiurl);
  const jsonobject = await response.json();

  // 遍历键值对并拼接成指定格式的字符串
  const combinedStr = Object.entries(jsonobject)
    .map(([key, value]) => `${key}:${value}`)
    .join(', ');
  
  // 将字符串放入数组,得到长度为1的结果
  const arr = [combinedStr];
  console.log(arr);
}

需求2:生成二维数组,每个子数组对应一组键值对

如果是要实现你提到的 [['name','iss'], ['lat',45.123], ['lng',12.456]] 这种格式,直接使用 Object.entries() 即可完成对象到二维数组的转换:

const apiurl = 'https://api.wheretheiss.at/v1/satellites/25544';

async function getArray(){
  const response = await fetch(apiurl);
  const jsonobject = await response.json();

  // Object.entries 直接返回键值对组成的二维数组
  const arr = Object.entries(jsonobject);
  console.log(arr);
}

原代码问题说明

原代码中 for(var i in jsonobject) 循环里,arr.push(i, jsonobject[i]) 会把键和值作为两个独立元素推入数组,所以最终得到的是扁平的一维数组。使用 Object.entries() 可以更简洁、安全地处理对象的键值对转换。

内容的提问来源于stack exchange,提问作者Karl Max Jander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:00:02