diff options
| author | Priyansh <[email protected]> | 2022-01-22 21:33:06 -0500 |
|---|---|---|
| committer | Priyansh <[email protected]> | 2022-01-22 21:33:06 -0500 |
| commit | 6156ba8bc5481e6ae916bc1aebea0651c257dff8 (patch) | |
| tree | 06056f0d47229b6dca1d81e790a0880ac0d058d9 /src/helpers/arrayFunctions.ts | |
| parent | 35a5843b68710e8bcde949d5c2e2f472dbb325e4 (diff) | |
| download | izuku.js-6156ba8bc5481e6ae916bc1aebea0651c257dff8.tar.xz izuku.js-6156ba8bc5481e6ae916bc1aebea0651c257dff8.zip | |
feat: function to load data from json and flattenJSON
Diffstat (limited to 'src/helpers/arrayFunctions.ts')
| -rw-r--r-- | src/helpers/arrayFunctions.ts | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/helpers/arrayFunctions.ts b/src/helpers/arrayFunctions.ts index 234e135..e6a6c50 100644 --- a/src/helpers/arrayFunctions.ts +++ b/src/helpers/arrayFunctions.ts @@ -54,3 +54,46 @@ export function range( } return rangeArray; } + +/** + * flattenJSON - converts a nested JSON object into a simple JSON object + * @param object: the object to be flattened + * @returns the flattened object + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function flattenJSON(data: any): any { + const result: any = {}; + function recurse(cur: any, prop: string) { + if (Object(cur) !== cur) { + result[prop] = cur; + } else if (Array.isArray(cur)) { + // eslint-disable-next-line no-var + for (var i = 0, l = cur.length; i < l; i++) + recurse(cur[i], prop + '[' + i + ']'); + if (l == 0) result[prop] = []; + } else { + let isEmpty = true; + for (const p in cur) { + isEmpty = false; + recurse(cur[p], prop ? prop + '.' + p : p); + } + if (isEmpty && prop) result[prop] = {}; + } + } + recurse(data, ''); + return result; +} + +/** + * isValidJSONObject - checks if the object is a valid JSON object or a valid JSON string + * @param object: the object to be checked + * @returns true if the object is a valid JSON object or a valid JSON string + */ +export function isValidJSONObject(object: any): boolean { + try { + JSON.parse(JSON.stringify(object)); + return true; + } catch (e) { + return false; + } +} |
