Skip to content

Commit

Permalink
fixed flattenObject
Browse files Browse the repository at this point in the history
  • Loading branch information
ppaska committed Nov 8, 2022
1 parent a3f0bec commit 280cb1a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ <h4>Data Pipe testing page. Do not expect anything here! </h4>
}

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)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
23 changes: 20 additions & 3 deletions src/array/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 280cb1a

Please sign in to comment.