如何将对象的allocation属性从对象类型转为数组类型(避免修改原对象)
实现数组对象属性转换且不修改原对象
可以通过Array.prototype.map()结合对象扩展运算符来完成需求,既实现属性结构转换,又完全避免修改原数组和原对象。
代码实现
const originalArray = [ { "allocation": { "name": "custom", "customAllocations": [ { "name": "Developed", "weight": 0.75 }, { "name": "Diversified", "weight": 0.1 }, { "name": "Global", "weight": 0.15 } ] } }, { "allocation": { "name": "custom", "customAllocations": [ { "name": "Developed", "weight": 0.35 }, { "name": "Conservative", "weight": 0.1 }, { "name": "Global", "weight": 0.55 } ] } } ]; // 执行转换 const transformedArray = originalArray.map(item => ({ ...item, allocation: [...item.allocation.customAllocations] }));
关键逻辑说明
map():遍历原数组并返回全新数组,原数组不会被任何修改。...item:复制原对象的所有属性,创建新对象实例,彻底切断与原对象的引用关联。[...item.allocation.customAllocations]:对原customAllocations数组做浅拷贝,确保新数组与原数组引用独立。如果需要完全隔离嵌套对象(比如后续要修改数组内的对象),可以替换为JSON.parse(JSON.stringify(item.allocation.customAllocations))实现深拷贝。
内容的提问来源于stack exchange,提问作者Ae Leung
相关产品推荐
相关产品推荐

