JavaScript:拆分含多元素Actions数组的对象并复制生成新数组
问题描述
给定如下JavaScript对象:
const parsedData = [ { "name": "Mathilda", "Infotypes": [ { "Infotype": "9000", "InfotypeCanonicalName": "AdditionalFieldsInfotype", "AdditionalFieldsInfotype": { "CompanyCode": "2303", } }, { "Infotype": "0000", "InfotypeCanonicalName": "Actions", "Actions": [ { "StartDate": "20121212", "ActionType": "01", }, { "StartDate": "20230401", "ActionType": "02", } ] } ] } ]
需求:当parsedData中的对象包含的Infotypes.Actions数组长度大于1时,执行以下操作:
- 复制该对象,复制后的对象数量与原
Actions数组长度一致 - 每个复制后的对象的
Actions数组仅保留原数组中的对应单个元素,长度为1
最终期望得到的updatedParsedData如下:
[ { "name": "Mathilda", "Infotypes": [ { "Infotype": "9000", "InfotypeCanonicalName": "AdditionalFieldsInfotype", "AdditionalFieldsInfotype": { "CompanyCode": "2303", } }, { "Infotype": "0000", "InfotypeCanonicalName": "Actions", "Actions": [ { "StartDate": "20121212", "ActionType": "01", } ] } ] }, { "name": "Mathilda", "Infotypes": [ { "Infotype": "9000", "InfotypeCanonicalName": "AdditionalFieldsInfotype", "AdditionalFieldsInfotype": { "CompanyCode": "2303", } }, { "Infotype": "0000", "InfotypeCanonicalName": "Actions", "Actions": [ { "StartDate": "20230401", "ActionType": "02", } ] } ] } ]
解决方案代码
可以通过遍历数据、深度复制对象并拆分Actions数组来实现需求,完整代码如下:
const parsedData = [ { "name": "Mathilda", "Infotypes": [ { "Infotype": "9000", "InfotypeCanonicalName": "AdditionalFieldsInfotype", "AdditionalFieldsInfotype": { "CompanyCode": "2303", } }, { "Infotype": "0000", "InfotypeCanonicalName": "Actions", "Actions": [ { "StartDate": "20121212", "ActionType": "01", }, { "StartDate": "20230401", "ActionType": "02", } ] } ] } ]; // 深度复制对象,避免修改新对象时影响原始数据 const deepClone = (obj) => JSON.parse(JSON.stringify(obj)); const updatedParsedData = []; parsedData.forEach((data) => { // 定位到包含多元素Actions的Infotype项 const targetInfo = data.Infotypes.find(info => Object.prototype.hasOwnProperty.call(info, 'Actions') && info.Actions.length > 1 ); if (targetInfo) { // 遍历每个Action元素,生成对应新对象 targetInfo.Actions.forEach(action => { const newData = deepClone(data); // 替换新对象中的Actions数组为当前单个元素 const newTargetInfo = newData.Infotypes.find(info => info.Infotype === '0000'); newTargetInfo.Actions = [action]; updatedParsedData.push(newData); }); } else { // 无符合条件的Actions时,直接保留原对象副本 updatedParsedData.push(deepClone(data)); } }); console.log(updatedParsedData);
关键说明
- 用
deepClone函数基于JSON序列化实现深度复制,避免对象引用导致的原始数据被修改 - 先定位到包含多元素
Actions的Infotype项,再遍历每个Action生成对应的新对象 - 对每个新对象,替换其
Actions数组为仅包含当前遍历到的单个Action元素
内容的提问来源于stack exchange,提问作者R.Almoued
相关产品推荐
相关产品推荐

