1 | export function addProperty(object, path, value) {
|
2 | const initialSegment = path[0];
|
3 | if (path.length === 1) {
|
4 | object[initialSegment] = value;
|
5 | return;
|
6 | }
|
7 | let field = object[initialSegment];
|
8 | if (field != null) {
|
9 | addProperty(field, path.slice(1), value);
|
10 | return;
|
11 | }
|
12 | if (typeof path[1] === 'string') {
|
13 | field = Object.create(null);
|
14 | }
|
15 | else {
|
16 | field = [];
|
17 | }
|
18 | addProperty(field, path.slice(1), value);
|
19 | object[initialSegment] = field;
|
20 | }
|
21 | export function getProperty(object, path) {
|
22 | if (!path.length || object == null) {
|
23 | return object;
|
24 | }
|
25 | const newPath = path.slice();
|
26 | const key = newPath.shift();
|
27 | if (key == null) {
|
28 | return;
|
29 | }
|
30 | const prop = object[key];
|
31 | return getProperty(prop, newPath);
|
32 | }
|
33 | export function getProperties(object, propertyTree) {
|
34 | if (object == null) {
|
35 | return object;
|
36 | }
|
37 | const newObject = Object.create(null);
|
38 | for (const key in propertyTree) {
|
39 | const subKey = propertyTree[key];
|
40 | if (subKey == null) {
|
41 | newObject[key] = object[key];
|
42 | continue;
|
43 | }
|
44 | const prop = object[key];
|
45 | newObject[key] = deepMap(prop, function deepMapFn(item) {
|
46 | return getProperties(item, subKey);
|
47 | });
|
48 | }
|
49 | return newObject;
|
50 | }
|
51 | export function propertyTreeFromPaths(paths) {
|
52 | const propertyTree = Object.create(null);
|
53 | for (const path of paths) {
|
54 | addProperty(propertyTree, path, null);
|
55 | }
|
56 | return propertyTree;
|
57 | }
|
58 | function deepMap(arrayOrItem, fn) {
|
59 | if (Array.isArray(arrayOrItem)) {
|
60 | return arrayOrItem.map(nestedArrayOrItem => deepMap(nestedArrayOrItem, fn));
|
61 | }
|
62 | return fn(arrayOrItem);
|
63 | }
|