magento2-api-wrapper
Version:
Minimal Magento 2 API library. Both node and browser compatible
37 lines (36 loc) • 1.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.flatten = void 0;
/**
* Flattens object/array to an object which keys are nested using square brackets
*/
function flatten(data) {
const flatten = flattenToArray(data);
return Object.fromEntries(flatten.map((v) => [
Array.isArray(v[0])
? (v[0].shift() + (v[0].map((p) => `[${p}]`)).join(""))
: v[0],
v[1],
]));
}
exports.flatten = flatten;
function flattenToArray(data) {
const flat = [];
for (const name in data) {
const value = data[name];
// copy non nested values
if (typeof value !== "object") {
flat.push([name, value]);
continue;
}
const flatValues = flattenToArray(value)
.map((v) => {
return [
Array.isArray(v[0]) ? [name, ...v[0]] : [name, v[0]],
v[1],
];
});
flat.push(...flatValues);
}
return flat;
}