/
remap.cjs
99 lines (79 loc) · 2.07 KB
/
remap.cjs
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
async function remap(arr, keyMap, iterator) {
const newArr = []
for (const item of arr) {
const mappedItem = {};
for (const key in keyMap) {
const sourceKey = keyMap[key];
const sourceKeyParts = sourceKey.split('.');
let value = item;
for (const part of sourceKeyParts) {
if (value === undefined) {
value = undefined; // Ensure undefined values are preserved
break;
}
if (part.includes('[')) {
const [arrayKey, index] = part.match(/([^[]*)\[(\d+)\]/).slice(1);
value = value[arrayKey][parseInt(index, 10)];
} else {
value = value[part];
}
}
notate(key, value, mappedItem);
}
if (iterator) {
await iterator(mappedItem)
}
newArr.push(mappedItem);
};
return newArr
}
function notate(notation, value, result) {
let currentObj = result || {};
if (typeof notation === 'object') {
let tempObj = value || {};
for (const key in notation) {
notate(key, notation[key], tempObj)
}
return tempObj
}
const keys = notation.split('.');
if (keys.length === 1) {
currentObj[keys[0]] = value
} else {
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const isArray = key.includes('[');
if (isArray) {
const [arrayKey, arrayIndex] = key.match(/([^[]*)\[(\d+)\]/).slice(1);
currentObj[arrayKey] = currentObj[arrayKey] || [];
currentObj = currentObj[arrayKey];
if (!currentObj[arrayIndex]) {
currentObj[arrayIndex] = {};
}
if (i === keys.length - 1) {
currentObj[arrayIndex] = value;
} else {
currentObj = currentObj[arrayIndex];
}
} else {
if (!currentObj[key]) {
if (i === keys.length - 1) {
currentObj[key] = value;
} else {
currentObj[key] = {};
}
}
currentObj = currentObj[key];
}
}
}
return currentObj
}
// export {
// remap,
// notate
// }
module.exports = {
remap,
notate
}