-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-utils.ts
57 lines (52 loc) · 1.62 KB
/
json-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { chunk, isPlainObject, merge, setWith } from 'lodash-es';
import { I18nJson } from '@/types/i18n-json';
import { Json } from '@/types/json';
export class JsonUtils {
/**
* Physical limit is 100000.
*/
public static readonly CHUNK_LIMIT: number = 99000;
static slice(json: I18nJson): I18nJson[] {
const values: I18nJson[] = JsonUtils.sliceByValue(json);
const chunks: I18nJson[][] = chunk(values, JsonUtils.CHUNK_LIMIT);
return chunks.map((c: I18nJson[]) => JsonUtils.mergeChunkValues(c));
}
/**
* Example input:
* const json = {
* en: {
* headers: {
* name: 'Name',
* user: 'User',
* },
* 'headers.company': 'Company',
* user: {
* role: ['Admin', 'Editor'],
* },
* },
* };
*
* Example result:
* const result = [
* { en: { headers: { name: 'Name' } } },
* { en: { headers: { user: 'User' } } },
* { en: { 'headers.company': 'Company' } },
* { en: { user: { role: ['Admin', 'Editor'] } } },
* ];
*/
protected static sliceByValue(json: Json, keys: string[] = []): Json[] {
return Object.entries(json).reduce((prev: Json[], [key, value]: [string, Json]) => {
if (isPlainObject(value)) {
prev.push(...JsonUtils.sliceByValue(value, [...keys, key]));
} else if (keys.length > 1) {
prev.push(setWith({}, [...keys, key].join('.'), value, Object));
} else {
prev.push({ [keys[0]]: { [key]: value } });
}
return prev;
}, []);
}
protected static mergeChunkValues(values: Json[]): Json {
return merge(...(values as [number, Json]));
}
}