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

如何用ES6移除对象数组中键名的-0、-1类后缀

问题描述

现有如下JavaScript对象数组:

[
    {'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0},
    {'contactTypeField-1': 'Index1', 'firstNameField-1': '1', 'uniqueRowField-1': 0}
]

需要移除每个对象键名中的-0、-1这类后缀,期望输出如下:

[
    {contactTypeField: 'Index0', firstNameField: '0', uniqueRowField: 0},
    {contactTypeField: 'Index1', firstNameField: '1', uniqueRowField: 0}
]

请问是否有合适的ES6方法实现该需求?

实现方案

完全可以用ES6的方法搞定,核心思路就是遍历数组里的每个对象,把每个对象的键名去掉末尾的-0、-1这类后缀,再重新拼成新对象。

直接上代码:

const originalArray = [
    {'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0},
    {'contactTypeField-1': 'Index1', 'firstNameField-1': '1', 'uniqueRowField-1': 0}
];

const processedArray = originalArray.map(obj => {
    return Object.entries(obj).reduce((newObj, [key, value]) => {
        // 用正则干掉键名末尾的-数字后缀
        const cleanedKey = key.replace(/-(\d+)$/, '');
        newObj[cleanedKey] = value;
        return newObj;
    }, {});
});

console.log(processedArray);

代码说明:

  • Array.prototype.map:遍历原数组中的每个对象,返回处理后的新对象组成的数组。
  • Object.entries(obj):将对象转换为键值对数组,比如把单个属性转换为['contactTypeField-0', 'Index0']的形式。
  • Array.prototype.reduce:遍历键值对数组,逐步构建新对象,其中replace(/-(\d+)$/, '')通过正则匹配并移除键名末尾的-加数字的后缀。

如果你的场景中,键名后缀不只是数字,而是-后面跟任意内容,也可以将正则修改为/-[^-]*$/,这样能适配更多情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:02:49