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

如何将API返回的对象数组转换为以ID为键的JSON对象?

Convert Array of Objects to Key-Value JSON Structure

Hey there! Converting that array of objects into the structure you want is a common task, and there are a couple of clean ways to do it in JavaScript (the go-to for JSON manipulation). Let's walk through them:

First, let's recap your input and desired output:

Input JSON:

[ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ]

Desired Output JSON:

{ "id1": { "data": "text" }, "id2": { "data": "text" } }

Method 1: Use Array.reduce() (Most Concise)

This is the idiomatic way to transform arrays into objects in JavaScript. The reduce method iterates over each item and builds up the result object step by step:

const input = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ];

const output = input.reduce((acc, item) => {
  // Use the item's id as the key, and assign the data property
  acc[item.id] = { data: item.data };
  // If you want to dynamically include all properties except id (scalable for future fields):
  // const { id, ...rest } = item;
  // acc[id] = rest;
  return acc;
}, {}); // Start with an empty object as the initial accumulator

console.log(JSON.stringify(output, null, 2));

Method 2: Use forEach Loop (More Explicit for Beginners)

If you prefer a step-by-step approach that’s easy to follow, a forEach loop works perfectly:

const input = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ];
const output = {};

input.forEach(item => {
  output[item.id] = { data: item.data };
  // Again, use destructuring for scalable property handling:
  // const { id, ...rest } = item;
  // output[id] = rest;
});

console.log(JSON.stringify(output, null, 2));

Both methods will give you exactly the structure you’re looking for. The reduce method is more concise and preferred in most production code, while forEach is great if you want to make the logic super clear for anyone reading your work.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:07:07