Following is a deeply nested object with properties recurring.
How to convert the following deeply nested object
const obj = {
prop1: {
properties: { value: {} },
},
prop2: {
properties: { subProp: { properties: { value: {} } } },
},
prop3: {
properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } },
},
};
into this :
const obj = {
prop1: { value: {} },
prop2: { subProp: { value: {} } },
prop3: { subProp: { subSubProp: { value: {} } } },
};
//if properties exists, else leave as it is (in each level)
You could build new objects and check if the value is an object and if properties
exists. Then take either properties
or the object for a recursive call.
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; }
Without 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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With