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

JavaScript中如何将带索引名称的字段值合并为数组?

问题:合并带索引字段的value为数组

需求

当字段name包含索引(例如created_at[0])时,将对应条目的value合并为数组,同时去除column和name中的索引部分;无索引的字段保持原有结构不变。

现有数据

[
    {
        "column": "created_at[0]",
        "name": "created_at[0]",
        "type": "range",
        "value": "2022-12-26 00:00:00"
    },
    {
        "column": "created_at[1]",
        "name": "created_at[1]",
        "type": "range",
        "value": "2023-12-26 23:59:59"
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "aa@gmail.com"
    }
]

期望转换结果

[
    {
        "column": "created_at",
        "name": "created_at",
        "type": "range",
        "value": ["2022-12-12 00:00:00", "2023-12-12 23:59:59"]
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "aa@gmail.com"
    }
]

尝试的代码(未成功)

const res = array?.reduce(
    (accumulator, value) => ({
        ...accumulator,
        [value.name?.split("[").shift()]: value.value,
    }),
    {}
);
console.log(res)

问题分析

这段代码存在几个关键问题:

  1. 同名字段的value会被后续迭代覆盖,无法实现数组合并
  2. 返回结果是对象格式,不符合目标数组结构要求
  3. 没有处理column、type等其他字段的保留与修正

正确实现代码

const array = [
    {
        "column": "created_at[0]",
        "name": "created_at[0]",
        "type": "range",
        "value": "2022-12-26 00:00:00"
    },
    {
        "column": "created_at[1]",
        "name": "created_at[1]",
        "type": "range",
        "value": "2023-12-26 23:59:59"
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "aa@gmail.com"
    }
];

const result = Object.values(array.reduce((acc, item) => {
    // 提取不带索引的基础字段名
    const baseName = item.name.split('[').shift();
    // 检查临时对象中是否已有该字段
    if (acc[baseName]) {
        // 已有则将当前value追加到数组
        acc[baseName].value.push(item.value);
    } else {
        // 无则创建新条目,修正column和name,初始化value格式
        acc[baseName] = {
            ...item,
            column: baseName,
            name: baseName,
            value: item.name.includes('[') ? [item.value] : item.value
        };
    }
    return acc;
}, {}));

console.log(result);

代码说明

  • 用reduce遍历原始数组,以不带索引的字段名为键构建临时对象,用于聚合同名字段
  • 若临时对象中已存在该字段,直接将当前条目value追加到对应数组
  • 若不存在,复制原条目属性,替换column和name为基础名称,并根据原name是否含索引决定value是数组还是原始值
  • 最后通过Object.values()将临时对象转换为目标数组结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:31:14