JSFiddle - React, Tailwind, and code Playground

by blparker

JavaScript

var json = {
    foo : 'bar',
    biz : 1,
    baz : {
        qux : 'quux',
        oof : {
            zib : 2
        }
    },
    corge : [ 0, 1, 2, 3 ]
};

/*var row = [];
var columns = null;
function convert(json, parent) {
    
    if(columns == null) {
        columns = getColumns(json);
        console.log(columns);
    }
    
    if(typeof json === 'object' && !(json instanceof Array)) {
        for(var prop in json) {
            if(typeof json[prop] === 'object' && !(json[prop] instanceof Array)) {
                return convert(json[prop]);
            }
            else {
                row.push(json[prop]);
            }
        }
    }
    
    return row.join(',');
}*/

//console.log(convert(json));

function FlattenJson(obj) {
    this.obj = obj;
    return this.init();
}

FlattenJson.prototype = {
    _columns : null,

    init : function() {
        this._getColumns(this.obj);
        console.log("### ", this._columns);
        this._getCases();
    },
    _getColumns : function(obj, parent) {
        if(!this._columns) this._columns = [];
        
        for(var prop in obj) {
            if(typeof obj[prop] === 'object') {
                if(parent) {
                    parent = parent + '_' + prop;
                }
                
                if(obj[prop] instanceof Array) {
                    var len = obj[prop].length;
                    for(var i = 0; i < len; i++) {
                        var key = ((parent != null) ? parent : prop) + '_' + i;
                        this._columns.push(key);
                    }
                }
                else {
                    this._getColumns(obj[prop], (parent != null) ? parent : prop);
                }
            }
            else {
                if(parent) {
                    this._columns.push(parent + '_' + prop);
                }
                else {
                    this._columns.push(prop);
                }
            }
        }
    },
    _getCases :...