0

If I have a json object, and I don't really know how complex it is, I would like to restructure it as following example, how can I write it in Javascript?

Assume that I have a json object as following:

{
    "a": 1,
    "b": {
            "c": 2,
            "d": {
                     "e": 3
                  }
         }
    "f": {
            "g": 4
         }
}

Now, I would like to have following expected result:

{
   "a": 1,
   "b.c": 2,
   "b.d.e": 3,
   "f.g": 4
}
alexlee11111
  • 87
  • 1
  • 10
  • Something very close to what you are looking for is already there. Check it out at https://www.w3resource.com/JSON/JSONPath-with-JavaScript.php. – Romeo Sierra Mar 02 '20 at 09:44

1 Answers1

1

There is a library that looks to do the job if you can make use of them: https://www.npmjs.com/package/flat

Or something like:

let original = {
    "a": 1,
    "b": {
        "c": 2,
        "d": {
            "e": 3
        }
    },
    "f": {
        "g": 4
    }
}

function flattenObj(obj, parent = '', res = {}){
    for(let key in obj){
        let propName = parent ? parent + '.' + key : key;
        if(typeof obj[key] == 'object'){
            flattenObj(obj[key], propName, res);
        } else {
            res[propName] = obj[key];
        }
    }
    return res;
}

let response = flattenObj(original)

console.log(response)
Thomas__
  • 320
  • 3
  • 13