Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mololab
GitHub Repository: mololab/json-translator
Path: blob/master/src/utils/json.ts
235 views
1
import _ from 'lodash';
2
3
export function flatten(
4
obj: any,
5
parentKey: string = '',
6
separator: string = '.'
7
): Record<string, any> {
8
return Object.entries(obj).reduce((acc, [key, value]) => {
9
const newKey = parentKey ? `${parentKey}${separator}${key}` : key;
10
11
if (_.isObject(value) && !Array.isArray(value)) {
12
Object.assign(acc, flatten(value, newKey, separator));
13
} else {
14
acc[newKey] = value;
15
}
16
17
return acc;
18
}, {} as Record<string, any>);
19
}
20
21