JavaScript/AngularJS如何修改对象属性名(移除指定后缀等需求)
属性名清理与自定义替换的JavaScript解决方案
原始需求
现有一段用于移除属性名中空格及非单词字符的JavaScript代码:
let result = rows.map(el => { let resultobj = {}; Object.entries(el).map(([key, val]) => { resultobj[key.split(" ").join("").replace(/\W+/g, '')] = val; return resultobj; }) return resultobj; })
需要添加逻辑:将属性名AgendaItem中的Item移除,仅保留Agenda。
更新后的尝试与问题
尝试添加File #替换为Legistar、LegistarID替换为Legistar的逻辑后,代码如下:
let result = rows.map(el => { let resultobj = {}; Object.entries(el).map(([key, val]) => { resultobj[key.split(" ").join("").replace(/\W+|Item$/g, '').replace("File #","Legistar").replace("LegistarID","Legistar")] = val; return resultobj; }) return resultobj; }) console.log(result);
但执行后发现File #并未替换成Legistar,反而变成了File,输出结果如下:
[ {File: '75588', Ver: '1', Agenda: '1', BoardsCommissionsandCommittees: 'Public Comment', Type: 'Public Comment', …}, {File: '75590', Ver: '1', Agenda: '2', BoardsCommissionsandCommittees: 'Lake Update', Type: 'Miscellaneous', …}, {File: '75592', Ver: '1', Agenda: '3', BoardsCommissionsandCommittees: 'Booking Pace Update:', Type: 'Miscellaneous', …}, {File: '75594', Ver: '1', Agenda: '4', BoardsCommissionsandCommittees: 'Finance Report: ', Type: 'Miscellaneous', …}, {File: '75595', Ver: '1', Agenda: '5', BoardsCommissionsandCommittees: 'Director’s Report: ', Type: 'Miscellaneous', …}, {File: '75596', Ver: '1', Agenda: '6', BoardsCommissionsandCommittees: 'Announcement from the Chair: , Chair', Type: 'Miscellaneous', …} ]
解决方案
问题出在替换顺序:先执行的空格及非单词字符清理,已经把File #里的空格和#去掉变成了File,后续的replace("File #","Legistar")自然找不到匹配项。正确逻辑是先做自定义替换,再做通用清理,同时优化AgendaItem的替换规则:
最终代码
let result = rows.map(el => { let resultobj = {}; Object.entries(el).forEach(([key, val]) => { // 先处理自定义替换规则 let processedKey = key .replace(/File #/g, 'Legistar') .replace(/LegistarID/g, 'Legistar') .replace(/AgendaItem/g, 'Agenda'); // 精准替换AgendaItem为Agenda // 再执行通用清理:移除空格和非单词字符 processedKey = processedKey.split(" ").join("").replace(/\W+/g, ''); resultobj[processedKey] = val; }); return resultobj; }); console.log(result);
关键说明
- 调整替换顺序:先处理自定义字符串替换,再执行通用清理,避免自定义规则中的特殊字符被提前清理。
- 精准替换
AgendaItem:用replace(/AgendaItem/g, 'Agenda')比Item$更精准,不会误改其他以Item结尾的属性名(如OtherItem)。 - 语义优化:用
forEach替代map,遍历仅用于构建新对象,无需返回数组,语义更清晰。
修改后,File #会先替换为Legistar,再经通用清理保留Legistar;AgendaItem会正确转为Agenda;LegistarID也会替换为Legistar,同时其他属性名的空格和非单词字符正常清理。
内容的提问来源于stack exchange,提问作者erasmo carlos
相关产品推荐
相关产品推荐

