Archived
2
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
definma-api/src/helpers/flatten.ts

41 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-08-10 12:35:08 +02:00
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 === 'spectrum.dpt') {
console.log('dpt');
result[prop + '.labels'] = cur.map(e => e[0]);
result[prop + '.values'] = cur.map(e => e[1]);
}
else if (Array.isArray(cur)) {
if (keepArray) {
result[prop] = cur;
}
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] = [];
}
}
}
else {
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;
}