1

I have javascript object like as

var obj = {
    param1 : {
        subParam1: 10,
        subParam2: 20
    },
    param2: 123
}

if need to convert it to object with keys only in root

obj = {
    'param1.subParam1' : 10,
    'param1.subParam2' : 20,
    'param2' : 123
}
Huangism
  • 16,278
  • 7
  • 48
  • 74
Oleg Patrushev
  • 255
  • 3
  • 16

2 Answers2

2

You can write a simple recursive function for this:

function flatten(obj) {

    var result = {},
        temp, key, subkey;

    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (Object.prototype.toString.call(obj[key]) == '[object Object]') {
                temp = flatten(obj[key]);
                for (subkey in temp) {
                    result[key + '.' + subkey] = temp[subkey];
                }
            }
            else result[key] = obj[key];
        }
    }

    return result;
}

Looks like it works as expected:

{param1.subParam1: 10, param1.subParam2: 20, param2: 123}
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

Some might call this dense, some might call it compact, some might call in obscure, some might call it elegant.

function flatten_object_into_dot_notation(obj) {

    return function _flatten(obj, prefix, result) {

        return Object.keys(obj).reduce(function(_, key) {
            var val = obj[key];
            key = prefix + key;

            if (val && typeof val==='object') { _flatten(val, key + '.', result); } 
            else { result[key] = val; }

            return result;
        }, result);

    }(obj, '', {});

}