import globals from '../globals';
export default function flatten (data, keepArray = false) { // flatten object: {a: {b: true}} -> {a.b: true}
const result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur || Object.keys(cur).length === 0) {
result[prop] = cur;
}
else if (prop === `${globals.spectrum.spectrum}.${globals.spectrum.dpt}`) {
result[prop + '.labels'] = cur.map(e => parseFloat(e[0]));
result[prop + '.values'] = cur.map(e => parseFloat(e[1]));
else if (Array.isArray(cur)) {
if (keepArray) {
else { // array to string
if (cur.length && (Object(cur[0]) !== cur || Object.keys(cur[0]).length === 0)) { // array of non-objects
result[prop] = '[' + cur.join(', ') + ']';
else {
let l = 0;
for(let i = 0, l = cur.length; i < l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
let isEmpty = true;
for (let p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
if (isEmpty && prop)
result[prop] = {};
recurse(data, '');
return result;