excel-remastered
Version:
Enhances readability of complex nested JSON data while converting to CSV
58 lines (57 loc) • 2.03 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
function getBody(jsonObjects, headers) {
if (!Array.isArray(jsonObjects)) {
jsonObjects = [jsonObjects];
}
function dfs(obj, path) {
var value = obj;
path.forEach(function (attribute) {
if (Array.isArray(value)) {
value = value.map(function (item) { return dfs(item, attribute.split('.')); });
value = value.flat();
value = value.filter(function (item) { return item !== undefined; });
if (value.some(Array.isArray)) {
value = value.map(function (item) {
if (Array.isArray(item) && item.length > 0) {
return JSON.stringify(item);
}
return item;
});
}
}
else {
value = (value && value[attribute]) || null;
}
});
return value;
}
var csvBodyArray = jsonObjects.map(function (obj) {
var row = headers.map(function (header) {
return dfs(obj, header.split('.'));
});
return row;
});
// Transpose the CSV data to 1NF
var transposedData = [];
csvBodyArray.forEach(function (row) {
row.forEach(function (value, index) {
if (Array.isArray(value)) {
value.forEach(function (element, subIndex) {
if (!transposedData[subIndex]) {
transposedData[subIndex] = [];
}
transposedData[subIndex][index] = element === null ? '' : element;
});
}
else {
if (!transposedData[0]) {
transposedData[0] = [];
}
transposedData[0][index] = value === null ? '' : value;
}
});
});
return transposedData;
}
exports.default = getBody;
;