salix/loopback/util/flatten.js

44 lines
1.2 KiB
JavaScript

/**
* Flattens an array of objects by converting each object into a flat structure.
*
* @param {Array} dataArray Array of objects to be flattened
* @return {Array} Array of flattened objects
*/
function flatten(dataArray) {
return dataArray.map(item => flattenObj(item.__data));
}
/**
* Recursively flattens an object, converting nested properties into a single level object
* with keys representing the original nested structure.
*
* @param {Object} data The object to be flattened
* @param {String} [prefix=''] Optional prefix for nested keys
* @return {Object} Flattened object
*/
function flattenObj(data, prefix = '') {
let result = {};
try {
for (let key in data) {
if (!data[key]) continue;
const newKey = prefix ? `${prefix}_${key}` : key;
const value = data[key];
if (typeof value === 'object' && value !== null && !Array.isArray(value))
Object.assign(result, flattenObj(value.__data, newKey));
else
result[newKey] = value;
}
} catch (error) {
console.error(error);
}
return result;
}
module.exports = {
flatten,
flattenObj,
};