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

如何在JavaScript中按字段分组数组,向指定键追加对象?

Got it, let's sort out this grouping task for you! You're trying to organize your array of objects by the category property—this is such a common JavaScript task, and there are a few simple ways to nail it. Let's walk through them:

Using Array.reduce() (the most concise approach)

reduce is perfect for accumulating values into a single object, which is exactly what we need here. Here's how to use it:

var res_data = [{"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"}];

const groupedData = res_data.reduce((accumulator, currentItem) => {
  // If the category doesn't exist in our result object yet, create an empty array for it
  if (!accumulator[currentItem.category]) {
    accumulator[currentItem.category] = [];
  }
  // Add the current item to its category's array
  accumulator[currentItem.category].push(currentItem);
  return accumulator;
}, {}); // Start with an empty object as our initial accumulator

console.log(groupedData);

This will output exactly the structure you're looking for. The accumulator holds our final grouped object, and we build it up one item at a time.

Using Array.forEach() (if you prefer explicit iteration)

Since you mentioned you tried an iterative approach, this might be closer to what you were working on. We'll manually loop through each item and build the grouped object:

var res_data = [{"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"}];

const groupedData = {};

res_data.forEach(item => {
  // Check if the category key exists—if not, initialize an empty array
  if (!groupedData[item.category]) {
    groupedData[item.category] = [];
  }
  // Push the current item into the correct category array
  groupedData[item.category].push(item);
});

console.log(groupedData);

This works the same way as the reduce method, just with a more explicit loop. It's great if you want to see every step of the iteration clearly.

Bonus: Simplified ES6+ Syntax

If you're working in an environment that supports modern JavaScript features, you can shorten the code even more using nullish coalescing assignment (??=):

const groupedData = res_data.reduce((acc, item) => {
  // Initialize the category array if it doesn't exist
  acc[item.category] ??= [];
  acc[item.category].push(item);
  return acc;
}, {});

This does the exact same thing as the first reduce example but with fewer lines of code.

All of these methods will give you the exact structure you need:

{"food": [{"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}], "drinks": [{"id": "3", "text": "CCC", "category": "drinks", "value": "3"}]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:49:28