0
let obj = {
        name: "Allen",
        age: 26,
        address: {
            city: "city1",
            dist: "dist1",
            state: "state1"
        },
        grandParent: {
            parent: {
                key1: "val1",
                key2: "val2",
                innerParent: {
                    innerParentKey1: "innerParentVal1",
                    innerParentKey2: "innerParentKey2",
                    innerParentKey3: "innerParentVal3"
                }
            },
            child: {
                childKey1: 'childVal1',
                childKey2: 'childVal2',
                childKey3: 'childVal3'
            }
        }
    }

I want to flatten the above object and result should be like below output: The Object can contain arrays also but I need to flaten only the object

obj2 = {
        "name": "Allen",
        "age": 26,
        "address/city": "city1",
        "address/dist": "dist1",
        "address/state": "state1",
        "grandParent/parent/key1": "val1",
        "grandParent/parent/key2": "val2",
        "grandParent/parent/innerParent/innerParentKey1": "innerParentVal1",
        "grandParent/parent/innerParent/innerParentKey2": "innerParentKey2",
        "grandParent/child/childKey1": "childVal1",
        "grandParent/child/childKey2": "childVal2",
        "grandParent/child/childKey3": "childVal3",
    }

Can anyone please help me with this?

Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19

1 Answers1

0

const flattenObj = (object) => {
    let finalObject = {};

    for (let i in object) {
        if (!object.hasOwnProperty(i)) continue;

        if (object[i] !== null && (typeof object[i]) == 'object') {
            let newObject = flattenObj(object[i]);
            for (let j in newObject) {
                if (!newObject.hasOwnProperty(j)) continue;

                finalObject[i + '/' + j] = newObject[j];
            }
        } else {
            finalObject[i] = object[i];
        }
    }
    return finalObject;
}
let obj = {
        name: "Allen",
        age: 26,
        address: {
            city: "city1",
            dist: "dist1",
            state: "state1"
        },
        grandParent: {
            parent: {
                key1: "val1",
                key2: "val2",
                innerParent: {
                    innerParentKey1: "innerParentVal1",
                    innerParentKey2: "innerParentKey2",
                    innerParentKey3: "innerParentVal3"
                }
            },
            child: {
                childKey1: 'childVal1',
                childKey2: 'childVal2',
                childKey3: 'childVal3'
            }
        }
    }
console.log(flattenObj(obj))
Dharman
  • 30,962
  • 25
  • 85
  • 135