Skip to content

Instantly share code, notes, and snippets.

@jasonliao
Created August 17, 2020 02:34
Show Gist options
  • Save jasonliao/02549cdb85daf3c0086cc92e65a7d9b3 to your computer and use it in GitHub Desktop.
Save jasonliao/02549cdb85daf3c0086cc92e65a7d9b3 to your computer and use it in GitHub Desktop.
get object all paths. use in object to excel or csv
/*
const obj = {
a 1,
b: [{
c: 1,
d: [{
e: 1
}, {
e: 2
}],
f: [{
g: 1
}, {
g:2
}, {
g: 3
}]
}
getPaths(obj)
a, b.c, b.d.e, f.g
1, 1, 1, 1
1, 1, 1, 2
1, 1, 1, 3
1, 1, 2, 1
1, 1, 2, 2
1, 1, 2, 3
*/
function getPaths(data: any) {
let paths: any[] = [];
Object.entries(data).forEach(([key, value]: [string, any]) => {
if (Object.prototype.toString.call(value) === '[object Object]') {
const subPaths = getPaths(value);
const tmpPaths = linkSubPaths(paths, subPaths, key);
paths = tmpPaths;
} else if (Array.isArray(value)) {
let tmpPaths: any = [];
value.forEach((item: any) => {
const subPaths = getPaths(item);
tmpPaths = tmpPaths.concat(linkSubPaths(paths, subPaths, key));
});
paths = tmpPaths;
} else {
const subPaths = [{ [key]: value }];
const tmpPaths = linkSubPaths(paths, subPaths, '');
paths = tmpPaths;
}
});
return paths;
}
function linkSubPaths(paths: any[], subPaths: any[], key: string) {
const tmpPaths: any[] = [];
subPaths.forEach((item) => {
const obj: any = {};
// add key prefixes
Object.entries(item).forEach(([subKey, subValue]: [string, any]) => {
obj[`${key ? `${key}.` : ''}${subKey}`] = subValue;
});
if (!paths.length) {
tmpPaths.push(obj);
}
paths.forEach((path) => {
tmpPaths.push({ ...obj, ...path });
});
});
return tmpPaths;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment