smartobject/ts/tools/toFlatObject.ts

30 lines
941 B
TypeScript
Raw Normal View History

2022-03-07 14:28:32 +00:00
export const toFlatObject = (objectArg: object) => {
2023-07-12 17:40:41 +00:00
const returnObject: { [key: string]: any } = {};
const extractLayer = (
subObject: { [key: string]: any },
pathArg: string,
loopProtection: object[]
) => {
2022-03-08 00:49:38 +00:00
if (loopProtection.indexOf(subObject) > -1) {
return;
}
2022-03-07 14:28:32 +00:00
if (subObject)
for (const key of Object.keys(subObject)) {
let localPathArg = pathArg;
2023-07-12 17:40:41 +00:00
if (typeof subObject[key] === 'object' && !(subObject[key] instanceof Array)) {
2022-03-07 14:28:32 +00:00
const newLoopbackArray = loopProtection.slice();
newLoopbackArray.push(subObject);
2023-07-12 17:40:41 +00:00
extractLayer(
subObject[key],
localPathArg ? (localPathArg += `.${key}`) : key,
newLoopbackArray
);
2022-03-07 14:28:32 +00:00
} else {
2023-07-12 17:40:41 +00:00
returnObject[localPathArg ? (localPathArg += `.${key}`) : key] = subObject[key];
2022-03-07 14:28:32 +00:00
}
}
2023-07-12 17:40:41 +00:00
};
2022-03-07 14:28:32 +00:00
extractLayer(objectArg, '', []);
return returnObject;
2023-07-12 17:40:41 +00:00
};