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

如何动态将含任意数量对象的数组按键名分组转换为目标对象?

Dynamic Conversion of Dataset Array to Object of Arrays

Got it, let's refactor your code to handle any number of objects and any dynamic keys in your dataset—no more hardcoding keys like date, data1, etc. Here are two clean, scalable approaches:

Approach 1: Handle Variable Object Structures (Flexible)

This method works even if objects in your dataset have different sets of keys (some might have extra fields, others might miss some). It automatically collects all unique keys from all objects:

var dataset = [
 { date: "1 Jan 2020", data1: 44, data2: 40 },
 { date: "2 Jan 2020", data1: 37, data2: 60 },
 { date: "3 Jan 2020", data1: 75, data2: 90 },
 { date: "4 Jan 2020", data1: 22, data2: 55, data3: 100 } // Extra key added!
];

var newDataset = {};

// Loop through each object in the dataset
dataset.forEach(item => {
  // Iterate over every key in the current object
  Object.keys(item).forEach(key => {
    // Initialize the array for this key if it doesn't exist yet
    if (!newDataset[key]) {
      newDataset[key] = [];
    }
    // Push the value to the corresponding array
    newDataset[key].push(item[key]);
  });
});

console.log(newDataset);

How it works:

  • dataset.forEach(item): Goes through each object in your input array.
  • Object.keys(item): Gets all the key names from the current object (no hardcoding!).
  • We check if newDataset already has an array for that key—if not, we create one. Then we add the current value to that array.

Approach 2: For Uniform Object Structures (Concise)

If you know all objects in your dataset have exactly the same keys, you can use this shorter version with map:

var dataset = [
 { date: "1 Jan 2020", data1: 44, data2: 40 },
 { date: "2 Jan 2020", data1: 37, data2: 60 },
 { date: "3 Jan 2020", data1: 75, data2: 90 }
];

var newDataset = {};

// Grab all keys from the first object (assumes all objects match)
const keys = Object.keys(dataset[0]);

// For each key, create an array of values from every object
keys.forEach(key => {
  newDataset[key] = dataset.map(item => item[key]);
});

console.log(newDataset);

How it works:

  • Object.keys(dataset[0]): Fetches all keys from the first object (since all objects are identical).
  • dataset.map(item => item[key]): Creates a new array by extracting the value of key from each object in the dataset. This is a more concise alternative to a for loop.

Both approaches eliminate the need to manually declare arrays for each key—they adapt automatically to whatever your dataset throws at you.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:38:14