Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as _ from 'lodash';
- /**
- *
- * @param {object} value
- * @returns {object}
- */
- export function flattenObject(value) {
- /**@type {object} */
- let toReturn = {};
- for (const i in value) {
- if (!value.hasOwnProperty(i)) {
- continue;
- }
- if (typeof value[i] == 'object') {
- const flatObject = flattenObject(value[i]);
- for (const x in flatObject) {
- if (!flatObject.hasOwnProperty(x)) continue;
- toReturn[i + '.' + x] = flatObject[x];
- }
- } else {
- toReturn[i] = value[i];
- }
- }
- return toReturn;
- }
- /////////////////////OR//////////////////////////////
- // @ts-check
- /**
- *
- * @param {object} object
- * @returns {Promise<object>}
- */
- export async function flatObjectAndSeparateThemByDot(object) {
- /**@type {object} */
- const res = {};
- /**
- *
- * @param {object} obj
- * @param {string} [current]
- */
- (function recurse(obj, current) {
- if (current && _.isArray(object[current])) {
- // this condition will ignore arrays
- res[current] = object[current];
- } else {
- for (const key in obj) {
- const value = obj[key];
- // joined keys with dot
- const newKey = current ? current + '.' + key : key;
- if (value && typeof value === 'object') {
- // it's a nested object, so do it again
- recurse(value, newKey);
- } else {
- // it's not an object, so set the property
- res[newKey] = value;
- }
- }
- }
- })(object);
- return res;
- }
- // Typescript version
- export async function flatObjectAndSeparateThemByDot(
- object: any,
- ): Promise<any> {
- const res: any = {};
- (function recurse(obj: any, current?: string) {
- if (current && _.isArray(object[current])) {
- // this condition will ignore arrays
- res[current] = object[current];
- } else {
- for (const key in obj) {
- const value = obj[key];
- // joined keys with dot
- const newKey = current ? current + '.' + key : key;
- if (value && typeof value === 'object') {
- // it's a nested object, so do it again
- recurse(value, newKey);
- } else {
- // it's not an object, so set the property
- res[newKey] = value;
- }
- }
- }
- })(object);
- return res;
- }
Add Comment
Please, Sign In to add comment