Best way to flatten JS object (keys and values) to a single depth array

前端 未结 10 930
梦毁少年i
梦毁少年i 2020-12-05 05:10

I have written this small function to get all keys and values of an object and store them into an array. The object might contain arrays as values...

Object {

10条回答
  •  [愿得一人]
    2020-12-05 05:38

    I wanted to flatten my deep object to one level depth. None of the above solutions worked for me.

    My input:

    {
        "user": {
            "key_value_map": {
                "CreatedDate": "123424",
                "Department": {
                    "Name": "XYZ"
                }
            }
        }
    }
    

    Expected output:

    {
        "user.key_value_map.CreatedDate": "123424",
        "user.key_value_map.Department.Name": "XYZ"
    }
    

    Code that worked for me:

    function flattenObject(ob) {
        var toReturn = {};
    
        for (var i in ob) {
            if (!ob.hasOwnProperty(i)) continue;
    
            if ((typeof ob[i]) == 'object' && ob[i] !== null) {
                var flatObject = flattenObject(ob[i]);
                for (var x in flatObject) {
                    if (!flatObject.hasOwnProperty(x)) continue;
    
                    toReturn[i + '.' + x] = flatObject[x];
                }
            } else {
                toReturn[i] = ob[i];
            }
        }
        return toReturn;
    }
    

提交回复
热议问题