以下是具有重复属性的深度嵌套对象。
如何转换以下深度嵌套的对象
const obj = {
prop1: {
properties: { value: {} },
},
prop2: {
properties: { subProp: { properties: { value: {} } } },
},
prop3: {
properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } },
},
};
Run Code Online (Sandbox Code Playgroud)
进入这个:
const obj = {
prop1: { value: {} },
prop2: { subProp: { value: {} } },
prop3: { subProp: { subSubProp: { value: {} } } },
};
//if properties exists, else leave as it is (in each level)
Run Code Online (Sandbox Code Playgroud)
您可以构建新对象并检查该值是否为对象以及是否properties存在。然后使用properties或 对象进行递归调用。
const
removeProperties = object => Object.fromEntries(Object
.entries(object)
.map(([key, value]) => [
key,
value && typeof value === 'object'
? removeProperties('properties' in value ? value.properties : value)
: value
])
),
obj = { prop1: { properties: { value: {} } }, prop2: { properties: { subProp: { properties: { value: {} } } } }, prop3: { properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } } } };
console.log(removeProperties(obj));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
const
removeProperties = object => Object
.entries(object)
.map(([key, value]) => [
key,
value && typeof value === 'object'
? removeProperties('properties' in value ? value.properties : value)
: value
])
.reduce((object, [key, value]) => ({ ...object, [key]: value }), {}),
obj = { prop1: { properties: { value: {} } }, prop2: { properties: { subProp: { properties: { value: {} } } } }, prop3: { properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } } } };
console.log(removeProperties(obj));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)