JSFiddle - React, Tailwind, and code Playground
JavaScript
var json = {
"first": {
"second": "example",
"third": {
"fourth": "example2",
"fifth": "example3",
}
}
};
console.log(JSON.stringify(flatten(json)));
function flatten(obj) {
var flattened = {};
for (var prop in obj)
if (obj.hasOwnProperty(prop)) {
//If it's an object, and not an array, then enter recursively (reduction case).
if (typeof obj[prop] === 'object' &&
Object.prototype.toString.call(obj[prop]) !== '[object Array]') {
var child = flatten(obj[prop]);
for (var p in child)
if (child.hasOwnProperty(p))
flattened[p] = child[p];
}
//Otherwise if it's a string, add to our flattened object (base case).
else if (typeof obj[prop] === 'string')
flattened[prop] = obj[prop];
}
return flattened;
}