如何筛选嵌套非数组对象的指定属性并重构结构?
非数组对象的结构转换实现
需求说明
原对象结构:
const MainObject = { Object1: { Factory: { total: 100, today: 20 }, Group: { total: 50, today: 10 }, Sector: { total: 30, today: 5 } }, Object2: { Factory: { total: 150, today: 25 }, Group: { total: 70, today: 12 }, Sector: { total: 40, today: 8 } } };
目标结构(以Variable1为Factory、Variable2为total为例):
{ Object1: { Factory: { total: 100 } }, Object2: { Factory: { total: 150 } } }
要求可硬编码指定Variable1(Factory/Group/Sector)和Variable2(total/today),处理非数组类型的对象。
实现方案
使用JavaScript的对象遍历方法Object.entries和Object.fromEntries完成转换,代码如下:
function transformObject(originalObj, variable1, variable2) { return Object.fromEntries( Object.entries(originalObj).map(([key, subObj]) => { const targetValue = { [variable1]: { [variable2]: subObj[variable1][variable2] } }; return [key, targetValue]; }) ); }
使用示例
// 示例:保留Factory下的today属性 const result = transformObject(MainObject, 'Factory', 'today'); console.log(result);
输出结果:
{ Object1: { Factory: { today: 20 } }, Object2: { Factory: { today: 25 } } }
注意事项
- 确保原对象的子对象中存在指定的
variable1和variable2属性,避免出现undefined;如需处理属性不存在的场景,可在函数中添加判断逻辑。 - 该方法适用于所有层级匹配的非数组嵌套对象结构。
内容的提问来源于stack exchange,提问作者Juan Francisco Ruiz
相关产品推荐
相关产品推荐

