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

如何将键数组与API返回的数组数据关联生成对象?

解决方案

你可以通过遍历API返回的每一组数据,将其与键数组arr的元素一一对应,生成目标对象。以下是几种常用的实现方式:

方法1:使用map + reduce

遍历data_from_api的每个子数组,通过reduce将键和值配对成对象:

const arr = ['cat', 'dog', 'horse'];
const data_from_api = [["cat_1", "dog_1", "horse_1"], ["cat_2", "dog_2", "horse_2"]];

const result = data_from_api.map(item => {
  return arr.reduce((obj, key, index) => {
    obj[key] = item[index];
    return obj;
  }, {});
});

console.log(result);
// 输出:
// [
//   { cat: 'cat_1', dog: 'dog_1', horse: 'horse_1' },
//   { cat: 'cat_2', dog: 'dog_2', horse: 'horse_2' }
// ]

方法2:使用map + forEach

这种方式逻辑更直观,遍历每个子数组的同时,通过键数组逐个赋值:

const arr = ['cat', 'dog', 'horse'];
const data_from_api = [["cat_1", "dog_1", "horse_1"], ["cat_2", "dog_2", "horse_2"]];

const result = data_from_api.map(item => {
  const obj = {};
  arr.forEach((key, index) => {
    obj[key] = item[index];
  });
  return obj;
});

console.log(result);
// 输出同上

方法3:使用map + Object.fromEntries

利用Object.fromEntries将键值对数组直接转为对象,代码更简洁:

const arr = ['cat', 'dog', 'horse'];
const data_from_api = [["cat_1", "dog_1", "horse_1"], ["cat_2", "dog_2", "horse_2"]];

const result = data_from_api.map(item => {
  const entries = arr.map((key, index) => [key, item[index]]);
  return Object.fromEntries(entries);
});

console.log(result);
// 输出同上

注意事项

  • 确保arr的长度和data_from_api中每个子数组的长度一致,否则会出现部分键对应值为undefined的情况。
  • 如果API返回的子数组长度可能大于arr,可根据需求决定是否忽略多余值,或添加边界处理逻辑。

内容的提问来源于stack exchange,提问作者Jnildes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:03:31