Skip to content

Commit cb93d7c

Browse files
wewoormumiao
authored andcommitted
feat(utils): add flatObject and normalizeFlattedObject functions
1 parent 48c8984 commit cb93d7c

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/common/utils.ts

+70
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,73 @@ export function mergeFunctions(...funcs) {
3232
export function randomId() {
3333
return Date.now() + Math.round(Math.random() * 1000);
3434
}
35+
36+
export function mergeObjects(source: object, target: object) {
37+
for (const prop in target) {
38+
if (typeof source[prop] === 'object' && target[prop]) {
39+
source[prop] = mergeObjects(source[prop], target[prop]);
40+
} else {
41+
source[prop] = target[prop];
42+
}
43+
}
44+
return source;
45+
}
46+
47+
/**
48+
* It's used convert an object to a flatted object,
49+
* eg: { a: { b: 'test' }}, result is : { 'a.b': 'test' }
50+
* @param target flat target
51+
*/
52+
export function flatObject(target: object): object {
53+
const flatted = {};
54+
const recurse = (parent: string, target: object) => {
55+
for (const prop in target) {
56+
if (prop) {
57+
const value = target[prop];
58+
const path = parent ? `${parent}.${prop}` : prop;
59+
if (typeof value === 'object') {
60+
recurse(path, value);
61+
} else {
62+
flatted[path] = value;
63+
}
64+
}
65+
}
66+
};
67+
recurse('', target);
68+
return flatted;
69+
}
70+
71+
/**
72+
* It's used convert a flatted object to a normal object,
73+
* eg: { 'a.b': 'test' }, result is : { a: { b: 'test' }}
74+
* @param target flat target
75+
*/
76+
export function normalizeFlattedObject(target: object): object {
77+
let normalized = {};
78+
79+
for (const prop in target) {
80+
if (prop) {
81+
const flattedProps = prop.split('.');
82+
let prevProp = '';
83+
let root = {};
84+
let prevObj = root;
85+
for (let i = 0; i < flattedProps.length; ++i) {
86+
if (i === flattedProps.length) break;
87+
const key = flattedProps[i];
88+
const current = { [key]: '' };
89+
90+
if (prevProp) {
91+
prevObj[prevProp] = current;
92+
}
93+
prevObj = current;
94+
prevProp = key;
95+
if (i === 0) {
96+
root = current;
97+
}
98+
}
99+
prevObj[prevProp] = target[prop];
100+
normalized = mergeObjects(normalized, root);
101+
}
102+
}
103+
return normalized;
104+
}

0 commit comments

Comments
 (0)