Node.js中根据后缀ID替换JSON指定键名的技术需求
Node.js 实现指定JSON字段的重命名逻辑
需求说明
现有一组JSON数据,其中部分Label_Field_ID_xxx格式的键对应值为RBS。需要实现逻辑:找到与这些键带有相同后缀ID的User_Answer_Field_ID_xxx键,将该键名替换为RBS并保留对应的值,最终得到目标JSON结构。
原始JSON数据
[ { "Author": "rps", "Label_Field_ID_1117189": "RBS", "User_Answer_Field_ID_1117189": "4532019166", "status": "In Bearbeitung" }, { "Author": "sps", "Label_Field_ID_1117230": "RBS", "User_Answer_Field_ID_1117230": "4232019179" } ]
目标JSON结构
[ { "Author": "rps", "Label_Field_ID_1117189": "RBS", "RBS": "4532019166", "status": "In Bearbeitung" }, { "Author": "sps", "Label_Field_ID_1117230": "RBS", "RBS": "4232019179" } ]
Node.js 实现代码
const originalData = [ { "Author": "rps", "Label_Field_ID_1117189": "RBS", "User_Answer_Field_ID_1117189": "4532019166", "status": "In Bearbeitung" }, { "Author": "sps", "Label_Field_ID_1117230": "RBS", "User_Answer_Field_ID_1117230": "4232019179" } ]; const transformedData = originalData.map(item => { const newItem = {...item}; // 遍历所有键,筛选符合条件的Label字段 Object.keys(newItem).forEach(key => { if (key.startsWith('Label_Field_ID_') && newItem[key] === 'RBS') { // 提取后缀ID const idSuffix = key.split('_').pop(); const answerKey = `User_Answer_Field_ID_${idSuffix}`; // 存在对应回答键时,重命名并删除原键 if (newItem.hasOwnProperty(answerKey)) { newItem['RBS'] = newItem[answerKey]; delete newItem[answerKey]; } } }); return newItem; }); console.log(JSON.stringify(transformedData, null, 2));
代码说明
- 用
map遍历原始数组,创建新对象避免修改原数据; - 遍历对象的所有键,筛选出以
Label_Field_ID_开头且值为RBS的键; - 提取该键的后缀ID,拼接出对应的
User_Answer_Field_ID_xxx键名; - 若存在该回答键,将其值赋值给新键
RBS,同时删除原回答键; - 最终返回处理后的对象数组。
内容的提问来源于stack exchange,提问作者mahantesh sapgole
相关产品推荐
相关产品推荐

