@opengis/fastify-table
Version:
core-plugins
51 lines (50 loc) • 2.19 kB
JavaScript
/* eslint-disable no-console */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-param-reassign */
// import config from '../../../../config.js';
export default function unflattenObject(flatObj) {
const res = Object.keys(flatObj || {}).reduce((acc, key) => {
const keys = key.split(".");
keys.reduce((nestedObj, part1, index) => {
// ! prevent npx vitest run from upper case -ing env variables
const part = process.env.VITEST ? part1.toLowerCase() : part1;
if (index === keys.length - 1) {
// json array
if (typeof flatObj[key] === "string" &&
flatObj[key].startsWith("[") &&
flatObj[key] !== "[object Object]") {
// console.log('unflatten aray', key);
try {
nestedObj[part] = JSON.parse(flatObj[key] || "{}");
}
catch (err) {
console.warn(`⚠️ Error parsing JSON for key ${key}:`, err.toString());
nestedObj[part] = flatObj[key]; // fallback to original value if parsing fails
}
}
else if (["true", "false"].includes(flatObj[key]) ||
(!isNaN(flatObj[key]) && false)) {
// console.log('unflatten number', key);
try {
nestedObj[part] = JSON.parse(flatObj[key] || "{}");
}
catch (err) {
console.warn(`⚠️ Error parsing JSON for key ${key}:`, err.toString());
nestedObj[part] = flatObj[key]; // fallback to original value if parsing fails
}
}
else {
// console.log('unflatten else', key);
nestedObj[part] = flatObj[key];
}
}
else {
nestedObj[part] = nestedObj[part] || {};
}
return nestedObj[part];
}, acc);
return acc;
}, {});
console.log("unflattened");
return res;
}