How to flatten a json

var obj={
        a:1,
        b:{
            b1:2,
            b2:3
        },
        c:{
            c1:4,
            c2:{
                c21:5,
                c21:6
            }
        }
    };
    //
    //return json={a:1,b.b1:2,b.b2:3,c.c1:4,c.c2.c21:5,c.c2.c22:6};

which god knows how to integrate this kind of data structure, it should be recursive, but how does that key value come out? do me a favor. Now I want to write a method that can be flattened when encountering this kind of data structure.

Apr.19,2021

look at this

(I just made a mistake.)

function outerFn (param){
    var result = {}
    function fn (obj,prefix) {
      for (key in obj){
       let fullKey = prefix?(prefix+'.'+key):key;
        if (typeof obj[key]==='object'){
            fn(obj[key],fullKey)
        }else{
          result[fullKey] = obj[key]
        }
      }
    }
    fn(param)
    return result;
}

function outerFn (param){
    var result = {}
    function fn(obj, prefix) {
        for (key in obj) {
            let fullKey = prefix ? (prefix + '.' + key) : key;
            if (typeof obj[key] === 'object') {
                fn(obj[key], fullKey)
            } else {
                result[fullKey] = obj[key]
            }
        }
    }
    fn(param);
    return result;
}
Menu