Covert Flat JSON to Nested JSON in Javascript

This is a code snippet to un-flatten Map or Flat JSON Object to Nested JSON object. This JavaScript method will help you convert Flat JSON to Nested JSON in JavaScript. Also the code is lint free and ready to use with SonarQube and ESLint Code Checkers.

export const unflatten = data => {
    "use strict";
    if ( Array.isArray(data) || Object(data) !== data)
        return data;
    const result = {};
    let cur, prop, idx, last, temp;
    for(const p of Object.keys(data)) {
        cur = result;
        prop = "";
        last = 0;
        do {
            idx = p.indexOf(".", last);
            temp = p.substring(last, idx !== -1 ? idx : undefined);
            if(!cur[prop]) {
                cur[prop] = (!isNaN(parseInt(temp)) ? [] : {});
            }
            cur = cur[prop]
            prop = temp;
            last = idx + 1;
        } while(idx >= 0);
        cur[prop] = data[p];
    }
    return result[""];
}

Output:

console.log(unflatten({'a.0.b': 0, 'a.1.c': 1, 'x.y.0': 7}));

// {a : [ {b: 0}, {c: 1} ], x: { y: [7] }}

Click here to change it back Convert Nested JSON to Flat JSON in JavaScript

Related Posts