JSFiddle - React, Tailwind, and code Playground

by gautamadude

JavaScript

var flatten = function(source,pathArray,result){
 
    pathArray                   = (typeof pathArray === 'undefined') ? [] : pathArray;
    result                      = (typeof result === 'undefined') ? {} : result;
 
    var key, value, newKey;
 
    for (var i in source) {
 
        if (source.hasOwnProperty(i)) {
 

            key                 = i;
            value               = source[i];
 
            pathArray.push(key);
 
            if (typeof value === 'object' && value !== null){
 
                result          = flatten(value,pathArray,result);
 
            } else {
 
                newKey          = pathArray.join('.');
                result[newKey]  = value;
            }
 
            pathArray.pop();
        }
    }
 
    return result;
};

var returnValues = function(obj, source) {

	var result = {};

	for (i in source) {
		if (source.hasOwnProperty(i)) {
			var place = obj;
			var flatProperty = i.split(".");
			place = place[flatProperty[0]];
			flatProperty.splice(0, 1);
			var where;
			var array = false;
			//If place in obj is an array
			//set where and array
			for (val in flatProperty) {
				where = flatProperty[val];
				if (Object.prototype.toString.call(place[where]) == "[object Array]") {
					array = flatProperty[parseInt(val)+1];
					break;
				} else if (Object.prototype.toString.call(place[where]) != "[object Object]") {
					break;
				} else {
					place = place[where]
				}
			}
			if (array) {
				place[where][array] = source[i];
			} else {
				place[where] = source[i];
			}
		}
	}
}

var obj = {
    foo : {
        bar : {
            baz : 'SUCCESS!',
            biz : [['first', "first2"],'second','third']
        }
    }
};

var flattened = flatten(obj);
for (key in flattened) break;
flattened[key] = "Failure!";
returnValues(obj, flattened);
console.log(obj);