Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object deep properties in to another?

Tags:

javascript

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)
like image 381
reacg garav Avatar asked Jun 13 '20 08:06

reacg garav


1 Answers

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; }
like image 141
Nina Scholz Avatar answered Oct 02 '22 13:10

Nina Scholz