Convert Nested JSON to Flat JSON in JavaScript

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

export const flatten = data => {
    var result = {};

    const handleArray = (cur, recurse, prop, result) => {
        const l = cur.length;
        for (let i = 0; i < l; i++)
            recurse(cur[i], prop ? prop + "." + i : "" + i);
        if (l == 0)
            result[prop] = [];
    }

    function recurse(cur, prop) {
        if (Array.isArray(cur)) {
            handleArray(cur, recurse, prop, result);
        } else if (Object(cur) !== cur) {
            result[prop] = cur;
        } else {
            let isEmpty = true;
            for (const p of Object.keys(cur)) {
                isEmpty = false;
                recurse(cur[p], prop ? prop + "." + p : p);
            }
            if (isEmpty)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
}

Output:

console.log(flatten({a : [ {b: 0}, {c: 1} ], x: { y: [7] }}));

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

Click here to change it back Covert Flat JSON to Nested JSON in Javascript

Related Posts