From 280cb1a303838cbbd1d560ec25d01cee48a2d9fa Mon Sep 17 00:00:00 2001 From: Pavlo Date: Tue, 8 Nov 2022 19:10:33 +0000 Subject: [PATCH] fixed flattenObject --- index.html | 2 +- package.json | 2 +- src/array/transform.ts | 23 ++++++++++++++++++++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/index.html b/index.html index b0fbdc9..b89383f 100644 --- a/index.html +++ b/index.html @@ -97,7 +97,7 @@

Data Pipe testing page. Do not expect anything here!

} function onButtonClick() { - const data = [{ a: 1, d:{d1:22, d2:33} }, { b: 2, d:{d1:221, d2:331} }]; + const data = [{ a: null, d:{d1:22, d2:33} }, { b: 2, d:{d1:221, d2:331, d3: null} }]; console.log('* fieldsInfo => ', dp.dataPipe(data).flattenObject()); // const json = `[{"value":"test value\\\\d"}]`; // console.log(json) diff --git a/package.json b/package.json index acb50a6..734ea12 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "datapipe-js", - "version": "0.3.28", + "version": "0.3.29", "description": "dataPipe is a data processing and data analytics library for JavaScript. Inspired by LINQ (C#) and Pandas (Python)", "main": "dist/cjs/data-pipe.js", "module": "dist/esm/data-pipe.mjs", diff --git a/src/array/transform.ts b/src/array/transform.ts index 74e7181..0374ac6 100644 --- a/src/array/transform.ts +++ b/src/array/transform.ts @@ -44,16 +44,33 @@ export function distinct(array: any[], elementSelector?: Selector): any[] { } return Array.from(new Set(array)); } - +/** + * Flatten Object or array of objects + * Object + * [{ a: 1, d:{d1: 22, d2: 33} }, { b: 2, d:{d1:221, d2:331} }] + * will become + * [{ a: 1, d.d1: 22, d.d2: 33 }, { b: 2, d.d1: 221, d.d2: 331 }] + * @param data + * @returns + */ export function flattenObject(data: any): any { + if (!data || typeof data !== 'object') { + return data; + } + function iterate(rootData: any, obj: any, prefix: string): void { const keys = Object.keys(rootData); for (let i = 0; i < keys.length; i++) { - const pName = prefix? `${prefix}.${keys[i]}`: keys[i]; + const pName = prefix ? `${prefix}.${keys[i]}` : keys[i]; const value = rootData[keys[i]]; - if (typeof value === 'object' && !(value instanceof Date)) { + if ( + typeof value === 'object' && + value !== null && + value !== undefined && + !(value instanceof Date) + ) { iterate(value, obj, pName); } else if (typeof value === 'function') { continue;