如何仅将对象中的简单属性克隆到另一个对象?
动态提取对象非数组属性生成新对象
需求是从目标对象中提取所有顶层非数组类型的属性,创建新对象,且新对象能自动适配原对象新增的非数组属性。
原对象示例
const obj = { "id": 5, "adress": "Test", "name": "Q1", "sections": [ { "code": "S1", "label": "LS1", "subSections": [ { "code": "S1-1", "label": 'LS1-1', "questions": [ { "code": "Q1", "label": "LQ1", "answer": [ { "code": "A1", "label": 'LA1', } ], } ] } ], } ] };
实现方案
方法1:遍历对象键筛选
通过遍历对象的所有顶层键,判断属性值是否为数组,仅保留非数组属性:
const newObj = {}; for (const key in obj) { // 排除数组类型的属性 if (!Array.isArray(obj[key])) { newObj[key] = obj[key]; } }
方法2:使用Object.entries和reduce简化写法
更简洁的函数式写法,同样实现动态筛选:
const newObj = Object.entries(obj).reduce((result, [key, value]) => { if (!Array.isArray(value)) { result[key] = value; } return result; }, {});
效果验证
当原对象新增非数组属性(比如date: "somedate")时,新对象会自动包含该属性:
// 新增属性后的原对象 const objWithDate = { "id": 5, "adress": "Test", "date": "somedate", "name": "Q1", "sections": [...] // 原数组属性 }; // 生成的newObj // { id: 5, adress: "Test", date: "somedate", name: "Q1" }
内容的提问来源于stack exchange,提问作者unittestangular2
相关产品推荐
相关产品推荐

