UNPKG

magento2-api-wrapper

Version:

Minimal Magento 2 API library. Both node and browser compatible

33 lines (32 loc) 893 B
/** * Flattens object/array to an object which keys are nested using square brackets */ export 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], ])); } 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; }