以下是一个深度嵌套的对象,其属性重复出现。
如何转换以下深度嵌套的对象
const obj = {
prop1: {
properties: { value: {} },
},
prop2: {
properties: { subProp: { properties: { value: {} } } },
},
prop3: {
properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } },
},
};
进入这个:
const obj = {
prop1: { value: {} },
prop2: { subProp: { value: {} } },
prop3: { subProp: { subSubProp: { value: {} } } },
};
//if properties exists, else leave as it is (in each level)
最佳答案
您可以构建新对象并检查该值是否为对象以及 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));
.as-console-wrapper { max-height: 100% !important; top: 0; }
没有
Object.fromEntries
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));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何将对象深层属性转换为另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62357525/