@x12i/helpers 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +43 -0
- package/index.js +4 -0
- package/package.json +35 -0
- package/src/helpers/objectsMapper.js +456 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 x12i
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# @x12i/helpers
|
|
2
|
+
|
|
3
|
+
Small helper utilities for x12i projects.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @x12i/helpers
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
### Objects mapper
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
const { mapObject, createMapper, mapArray, deepGet, deepSet } = require("@x12i/helpers");
|
|
17
|
+
|
|
18
|
+
const source = { user: { first: "Jane", last: "Doe" } };
|
|
19
|
+
|
|
20
|
+
const mapping = [
|
|
21
|
+
"user.first -> profile.firstName",
|
|
22
|
+
"user.last -> profile.lastName",
|
|
23
|
+
{ template: "{user.first} {user.last}", to: "profile.displayName" }
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
console.log(mapObject(source, mapping));
|
|
27
|
+
// { profile: { firstName: 'Jane', lastName: 'Doe', displayName: 'Jane Doe' } }
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
You can also import the mapper directly:
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
const { mapObject } = require("@x12i/helpers/objects-mapper");
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## API
|
|
37
|
+
|
|
38
|
+
- `mapObject(source, mapping, opts)`
|
|
39
|
+
- `createMapper(mapping, opts)`
|
|
40
|
+
- `mapArray(sourceArray, mapping, opts)`
|
|
41
|
+
- `deepGet(obj, path)`
|
|
42
|
+
- `deepSet(obj, path, value)`
|
|
43
|
+
|
package/index.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@x12i/helpers",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Small helper utilities for x12i projects.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "x12i",
|
|
7
|
+
"homepage": "https://www.npmjs.com/package/@x12i/helpers",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": ""
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"helpers",
|
|
14
|
+
"utilities",
|
|
15
|
+
"mapper",
|
|
16
|
+
"json",
|
|
17
|
+
"object-mapping"
|
|
18
|
+
],
|
|
19
|
+
"type": "commonjs",
|
|
20
|
+
"main": "./index.js",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./index.js",
|
|
23
|
+
"./objects-mapper": "./src/helpers/objectsMapper.js"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"index.js",
|
|
27
|
+
"src/",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"test": "node --test"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ╔══════════════════════════════════════════════════════════════╗
|
|
3
|
+
* ║ JSON OBJECT MAPPER ║
|
|
4
|
+
* ╠══════════════════════════════════════════════════════════════╣
|
|
5
|
+
* ║ Maps properties from a source JSON object to a target ║
|
|
6
|
+
* ║ JSON object using a flexible mapping configuration. ║
|
|
7
|
+
* ╚══════════════════════════════════════════════════════════════╝
|
|
8
|
+
*
|
|
9
|
+
* MAPPING CONFIG — each entry can be:
|
|
10
|
+
*
|
|
11
|
+
* ┌─────────────────────────────────────────────────────────────┐
|
|
12
|
+
* │ STRING shorthand │
|
|
13
|
+
* │ "user.name" → copies source.user.name to same path │
|
|
14
|
+
* │ "user.name -> profile.fullName" → renames path │
|
|
15
|
+
* ├─────────────────────────────────────────────────────────────┤
|
|
16
|
+
* │ OBJECT (full power) │
|
|
17
|
+
* │ { │
|
|
18
|
+
* │ from: "a.b.c" | ["a.b", "x.y"] | null, │
|
|
19
|
+
* │ to: "d.e.f", │
|
|
20
|
+
* │ transform: (val, source) => ..., │
|
|
21
|
+
* │ default: any, // if source value missing │
|
|
22
|
+
* │ condition: (val, source) => bool, │
|
|
23
|
+
* │ flatten: true, // spread object into target │
|
|
24
|
+
* │ arrayMap: subMappingConfig, // map each array elem │
|
|
25
|
+
* │ coerce: "string"|"number"|"boolean"|"array"|"date",│
|
|
26
|
+
* │ fallback: ["a.b", "c.d"], // first non-null wins │
|
|
27
|
+
* │ compute: (source) => any, // ignore `from`, build │
|
|
28
|
+
* │ template: "Hello {user.first} {user.last}", │
|
|
29
|
+
* │ pick: ["a","b"], // pick keys from sub-obj │
|
|
30
|
+
* │ omit: ["c","d"], // omit keys from sub-obj │
|
|
31
|
+
* │ rename: {old: "new"}, // rename keys in sub-obj │
|
|
32
|
+
* │ } │
|
|
33
|
+
* ├─────────────────────────────────────────────────────────────┤
|
|
34
|
+
* │ WILDCARD paths │
|
|
35
|
+
* │ "items[*].name -> products[*].title" │
|
|
36
|
+
* │ Maps every element in an array at that depth. │
|
|
37
|
+
* └─────────────────────────────────────────────────────────────┘
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
// ─── Helpers ──────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Parse a dot/bracket path into segments.
|
|
44
|
+
* "a.b[0].c[*]" → ["a","b","0","c","*"]
|
|
45
|
+
*/
|
|
46
|
+
function parsePath(path) {
|
|
47
|
+
if (!path || typeof path !== "string") return [];
|
|
48
|
+
return path
|
|
49
|
+
.replace(/\[(\w+|\*)]/g, ".$1")
|
|
50
|
+
.split(".")
|
|
51
|
+
.filter(Boolean);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Safely get a deep value. Supports [*] wildcard to fan-out over arrays.
|
|
56
|
+
*/
|
|
57
|
+
function deepGet(obj, path, MISSING = undefined) {
|
|
58
|
+
const segs = typeof path === "string" ? parsePath(path) : path;
|
|
59
|
+
if (!segs.length) return obj;
|
|
60
|
+
|
|
61
|
+
let current = obj;
|
|
62
|
+
for (let i = 0; i < segs.length; i++) {
|
|
63
|
+
if (current == null) return MISSING;
|
|
64
|
+
const seg = segs[i];
|
|
65
|
+
|
|
66
|
+
if (seg === "*") {
|
|
67
|
+
// Fan-out: apply remaining path to every element
|
|
68
|
+
if (!Array.isArray(current)) return MISSING;
|
|
69
|
+
const rest = segs.slice(i + 1);
|
|
70
|
+
return rest.length
|
|
71
|
+
? current.map((el) => deepGet(el, rest, MISSING))
|
|
72
|
+
: current;
|
|
73
|
+
}
|
|
74
|
+
current = current[seg];
|
|
75
|
+
}
|
|
76
|
+
return current === undefined ? MISSING : current;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Safely set a deep value. Creates intermediate objects/arrays as needed.
|
|
81
|
+
* [*] in target path means "append / map into array".
|
|
82
|
+
*/
|
|
83
|
+
function deepSet(obj, path, value) {
|
|
84
|
+
const segs = typeof path === "string" ? parsePath(path) : path;
|
|
85
|
+
if (!segs.length) return;
|
|
86
|
+
|
|
87
|
+
let current = obj;
|
|
88
|
+
for (let i = 0; i < segs.length - 1; i++) {
|
|
89
|
+
const seg = segs[i];
|
|
90
|
+
const next = segs[i + 1];
|
|
91
|
+
|
|
92
|
+
if (seg === "*") {
|
|
93
|
+
// Fan-out set: value should be an array
|
|
94
|
+
if (!Array.isArray(current)) return;
|
|
95
|
+
const rest = segs.slice(i + 1);
|
|
96
|
+
const vals = Array.isArray(value) ? value : current.map(() => value);
|
|
97
|
+
current.forEach((el, idx) => {
|
|
98
|
+
if (el && typeof el === "object") {
|
|
99
|
+
deepSet(el, rest, vals[idx]);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (current[seg] == null) {
|
|
106
|
+
current[seg] = next === "*" || /^\d+$/.test(next) ? [] : {};
|
|
107
|
+
}
|
|
108
|
+
current = current[seg];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const last = segs[segs.length - 1];
|
|
112
|
+
if (last === "*") {
|
|
113
|
+
// Push or spread into array
|
|
114
|
+
if (Array.isArray(current) && Array.isArray(value)) {
|
|
115
|
+
value.forEach((v, i) => (current[i] = v));
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
current[last] = value;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Deep merge: source properties into target without overwriting existing.
|
|
124
|
+
*/
|
|
125
|
+
function deepMerge(target, source) {
|
|
126
|
+
if (!source || typeof source !== "object") return target;
|
|
127
|
+
for (const key of Object.keys(source)) {
|
|
128
|
+
if (
|
|
129
|
+
target[key] &&
|
|
130
|
+
typeof target[key] === "object" &&
|
|
131
|
+
typeof source[key] === "object" &&
|
|
132
|
+
!Array.isArray(target[key])
|
|
133
|
+
) {
|
|
134
|
+
deepMerge(target[key], source[key]);
|
|
135
|
+
} else if (target[key] === undefined) {
|
|
136
|
+
target[key] = source[key];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return target;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ─── Coercion ─────────────────────────────────────────────────────
|
|
143
|
+
|
|
144
|
+
const COERCIONS = {
|
|
145
|
+
string: (v) => (v == null ? "" : String(v)),
|
|
146
|
+
number: (v) => {
|
|
147
|
+
const n = Number(v);
|
|
148
|
+
return Number.isNaN(n) ? 0 : n;
|
|
149
|
+
},
|
|
150
|
+
boolean: (v) =>
|
|
151
|
+
v === "false" || v === "0" || v === "no" ? false : Boolean(v),
|
|
152
|
+
array: (v) => (v == null ? [] : Array.isArray(v) ? v : [v]),
|
|
153
|
+
date: (v) => (v instanceof Date ? v : new Date(v)),
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// ─── Template interpolation ───────────────────────────────────────
|
|
157
|
+
|
|
158
|
+
function interpolate(template, source) {
|
|
159
|
+
return template.replace(/\{([^}]+)}/g, (_, path) => {
|
|
160
|
+
const val = deepGet(source, path.trim());
|
|
161
|
+
return val == null ? "" : String(val);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ─── Core mapper ──────────────────────────────────────────────────
|
|
166
|
+
|
|
167
|
+
const MISSING = Symbol("MISSING");
|
|
168
|
+
|
|
169
|
+
function processRule(rule, source) {
|
|
170
|
+
// ── Normalize shorthand strings ──
|
|
171
|
+
if (typeof rule === "string") {
|
|
172
|
+
if (rule.includes("->")) {
|
|
173
|
+
const [from, to] = rule.split("->").map((s) => s.trim());
|
|
174
|
+
rule = { from, to };
|
|
175
|
+
} else {
|
|
176
|
+
rule = { from: rule, to: rule };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const {
|
|
181
|
+
from,
|
|
182
|
+
to,
|
|
183
|
+
transform,
|
|
184
|
+
default: defaultVal,
|
|
185
|
+
condition,
|
|
186
|
+
flatten,
|
|
187
|
+
arrayMap,
|
|
188
|
+
coerce,
|
|
189
|
+
fallback,
|
|
190
|
+
compute,
|
|
191
|
+
template,
|
|
192
|
+
pick,
|
|
193
|
+
omit,
|
|
194
|
+
rename,
|
|
195
|
+
} = rule;
|
|
196
|
+
|
|
197
|
+
// ── Compute (ignore `from`, generate from whole source) ──
|
|
198
|
+
if (compute) {
|
|
199
|
+
const val = compute(source);
|
|
200
|
+
if (condition && !condition(val, source)) return { skip: true };
|
|
201
|
+
return { to, value: val };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── Template interpolation ──
|
|
205
|
+
if (template) {
|
|
206
|
+
const val = interpolate(template, source);
|
|
207
|
+
if (condition && !condition(val, source)) return { skip: true };
|
|
208
|
+
return { to, value: val };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ── Resolve source value ──
|
|
212
|
+
let value = MISSING;
|
|
213
|
+
|
|
214
|
+
if (fallback) {
|
|
215
|
+
// Try each path until one yields a non-null
|
|
216
|
+
for (const path of fallback) {
|
|
217
|
+
const v = deepGet(source, path, MISSING);
|
|
218
|
+
if (v !== MISSING && v != null) {
|
|
219
|
+
value = v;
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
} else if (Array.isArray(from)) {
|
|
224
|
+
// Multi-source → array of values (fed into transform)
|
|
225
|
+
value = from.map((p) => deepGet(source, p, MISSING));
|
|
226
|
+
if (value.every((v) => v === MISSING)) value = MISSING;
|
|
227
|
+
} else if (from) {
|
|
228
|
+
value = deepGet(source, from, MISSING);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ── Default ──
|
|
232
|
+
if ((value === MISSING || value == null) && defaultVal !== undefined) {
|
|
233
|
+
value = typeof defaultVal === "function" ? defaultVal(source) : defaultVal;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (value === MISSING) value = undefined;
|
|
237
|
+
|
|
238
|
+
// ── Condition gate ──
|
|
239
|
+
if (condition && !condition(value, source)) return { skip: true };
|
|
240
|
+
|
|
241
|
+
// ── Transform ──
|
|
242
|
+
if (transform) value = transform(value, source);
|
|
243
|
+
|
|
244
|
+
// ── Coerce ──
|
|
245
|
+
if (coerce && COERCIONS[coerce]) value = COERCIONS[coerce](value);
|
|
246
|
+
|
|
247
|
+
// ── Array sub-mapping ──
|
|
248
|
+
if (arrayMap && Array.isArray(value)) {
|
|
249
|
+
value = value.map((item) => mapObject(item, arrayMap));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ── Pick / Omit / Rename keys on sub-objects ──
|
|
253
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
254
|
+
if (pick) {
|
|
255
|
+
value = Object.fromEntries(
|
|
256
|
+
Object.entries(value).filter(([k]) => pick.includes(k))
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
if (omit) {
|
|
260
|
+
value = Object.fromEntries(
|
|
261
|
+
Object.entries(value).filter(([k]) => !omit.includes(k))
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
if (rename) {
|
|
265
|
+
const renamed = {};
|
|
266
|
+
for (const [k, v] of Object.entries(value)) {
|
|
267
|
+
renamed[rename[k] || k] = v;
|
|
268
|
+
}
|
|
269
|
+
value = renamed;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return { to, value, flatten };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ─── Public API ───────────────────────────────────────────────────
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Map a source object to a new target object.
|
|
280
|
+
*
|
|
281
|
+
* @param {object} source – the input JSON object
|
|
282
|
+
* @param {Array} mapping – array of mapping rules (strings or objects)
|
|
283
|
+
* @param {object} [opts]
|
|
284
|
+
* @param {object} [opts.base] – starting target object (default {})
|
|
285
|
+
* @param {boolean} [opts.stripNull] – remove null/undefined from output
|
|
286
|
+
* @param {boolean} [opts.passThrough]– copy unmapped source props as-is
|
|
287
|
+
* @param {function} [opts.onError] – (error, rule) => void
|
|
288
|
+
* @returns {object}
|
|
289
|
+
*/
|
|
290
|
+
function mapObject(source, mapping, opts = {}) {
|
|
291
|
+
const { base = {}, stripNull = false, passThrough = false, onError } = opts;
|
|
292
|
+
|
|
293
|
+
// Deep-clone base to avoid mutations
|
|
294
|
+
const target = JSON.parse(JSON.stringify(base));
|
|
295
|
+
|
|
296
|
+
// Pass-through: start with a copy of source
|
|
297
|
+
if (passThrough) deepMerge(target, JSON.parse(JSON.stringify(source)));
|
|
298
|
+
|
|
299
|
+
for (const rule of mapping) {
|
|
300
|
+
try {
|
|
301
|
+
const result = processRule(rule, source);
|
|
302
|
+
if (result.skip) continue;
|
|
303
|
+
|
|
304
|
+
const { to: targetPath, value, flatten: shouldFlatten } = result;
|
|
305
|
+
|
|
306
|
+
if (shouldFlatten && value && typeof value === "object") {
|
|
307
|
+
// Spread value's keys into target at the parent path
|
|
308
|
+
if (targetPath) {
|
|
309
|
+
const existing = deepGet(target, targetPath) || {};
|
|
310
|
+
deepSet(target, targetPath, { ...existing, ...value });
|
|
311
|
+
} else {
|
|
312
|
+
Object.assign(target, value);
|
|
313
|
+
}
|
|
314
|
+
} else if (targetPath) {
|
|
315
|
+
if (stripNull && (value === null || value === undefined)) continue;
|
|
316
|
+
deepSet(target, targetPath, value);
|
|
317
|
+
}
|
|
318
|
+
} catch (err) {
|
|
319
|
+
if (onError) onError(err, rule);
|
|
320
|
+
else console.warn(`[mapper] Rule failed:`, rule, err.message);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return target;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Create a reusable mapper function from a mapping config.
|
|
329
|
+
*/
|
|
330
|
+
function createMapper(mapping, opts = {}) {
|
|
331
|
+
return (source) => mapObject(source, mapping, opts);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Map each element of an array.
|
|
336
|
+
*/
|
|
337
|
+
function mapArray(sourceArray, mapping, opts = {}) {
|
|
338
|
+
return sourceArray.map((item) => mapObject(item, mapping, opts));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ─── Exports ──────────────────────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
module.exports = { mapObject, createMapper, mapArray, deepGet, deepSet };
|
|
344
|
+
|
|
345
|
+
// ══════════════════════════════════════════════════════════════════
|
|
346
|
+
// DEMO — run with: node json-mapper.js
|
|
347
|
+
// ══════════════════════════════════════════════════════════════════
|
|
348
|
+
|
|
349
|
+
if (require.main === module) {
|
|
350
|
+
const source = {
|
|
351
|
+
user: {
|
|
352
|
+
firstName: "Jane",
|
|
353
|
+
lastName: "Doe",
|
|
354
|
+
email: "jane@example.com",
|
|
355
|
+
age: "29",
|
|
356
|
+
address: {
|
|
357
|
+
street: "123 Main St",
|
|
358
|
+
city: "Springfield",
|
|
359
|
+
zip: "62704",
|
|
360
|
+
country: "US",
|
|
361
|
+
},
|
|
362
|
+
tags: ["admin", "editor"],
|
|
363
|
+
},
|
|
364
|
+
orders: [
|
|
365
|
+
{ id: 1, product: "Widget", qty: 3, price: 9.99 },
|
|
366
|
+
{ id: 2, product: "Gadget", qty: 1, price: 24.5 },
|
|
367
|
+
],
|
|
368
|
+
metadata: { createdAt: "2024-01-15T08:00:00Z", version: 2 },
|
|
369
|
+
legacyName: null,
|
|
370
|
+
nickname: "JD",
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
const mapping = [
|
|
374
|
+
// ── String shorthand: same path ──
|
|
375
|
+
"user.email",
|
|
376
|
+
|
|
377
|
+
// ── String shorthand: rename ──
|
|
378
|
+
"user.firstName -> profile.first",
|
|
379
|
+
"user.lastName -> profile.last",
|
|
380
|
+
|
|
381
|
+
// ── Coerce string → number ──
|
|
382
|
+
{ from: "user.age", to: "profile.age", coerce: "number" },
|
|
383
|
+
|
|
384
|
+
// ── Template interpolation ──
|
|
385
|
+
{
|
|
386
|
+
template: "{user.firstName} {user.lastName}",
|
|
387
|
+
to: "profile.displayName",
|
|
388
|
+
},
|
|
389
|
+
|
|
390
|
+
// ── Nested pick + rename ──
|
|
391
|
+
{
|
|
392
|
+
from: "user.address",
|
|
393
|
+
to: "profile.location",
|
|
394
|
+
pick: ["city", "country"],
|
|
395
|
+
rename: { country: "countryCode" },
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
// ── Fallback: first non-null wins ──
|
|
399
|
+
{ fallback: ["legacyName", "nickname", "user.firstName"], to: "profile.name" },
|
|
400
|
+
|
|
401
|
+
// ── Conditional ──
|
|
402
|
+
{
|
|
403
|
+
from: "user.age",
|
|
404
|
+
to: "profile.seniorDiscount",
|
|
405
|
+
transform: (v) => Number(v) >= 65,
|
|
406
|
+
condition: (v) => v != null,
|
|
407
|
+
},
|
|
408
|
+
|
|
409
|
+
// ── Array sub-mapping ──
|
|
410
|
+
{
|
|
411
|
+
from: "orders",
|
|
412
|
+
to: "purchases",
|
|
413
|
+
arrayMap: [
|
|
414
|
+
"id",
|
|
415
|
+
"product -> name",
|
|
416
|
+
{ from: "qty", to: "quantity" },
|
|
417
|
+
{ from: "price", to: "unitPrice" },
|
|
418
|
+
{
|
|
419
|
+
compute: (item) => +(item.qty * item.price).toFixed(2),
|
|
420
|
+
to: "total",
|
|
421
|
+
},
|
|
422
|
+
],
|
|
423
|
+
},
|
|
424
|
+
|
|
425
|
+
// ── Compute from whole source ──
|
|
426
|
+
{
|
|
427
|
+
compute: (src) => src.orders.reduce((s, o) => s + o.qty * o.price, 0),
|
|
428
|
+
to: "summary.orderTotal",
|
|
429
|
+
transform: (v) => +v.toFixed(2),
|
|
430
|
+
},
|
|
431
|
+
|
|
432
|
+
// ── Multi-source transform ──
|
|
433
|
+
{
|
|
434
|
+
from: ["user.tags", "metadata.version"],
|
|
435
|
+
to: "meta.info",
|
|
436
|
+
transform: ([tags, ver]) => ({
|
|
437
|
+
tagCount: tags.length,
|
|
438
|
+
apiVersion: `v${ver}`,
|
|
439
|
+
}),
|
|
440
|
+
},
|
|
441
|
+
|
|
442
|
+
// ── Flatten into root ──
|
|
443
|
+
{
|
|
444
|
+
from: "metadata",
|
|
445
|
+
flatten: true,
|
|
446
|
+
pick: ["createdAt"],
|
|
447
|
+
},
|
|
448
|
+
];
|
|
449
|
+
|
|
450
|
+
const result = mapObject(source, mapping);
|
|
451
|
+
|
|
452
|
+
console.log("═══ SOURCE ═══");
|
|
453
|
+
console.log(JSON.stringify(source, null, 2));
|
|
454
|
+
console.log("\n═══ RESULT ═══");
|
|
455
|
+
console.log(JSON.stringify(result, null, 2));
|
|
456
|
+
}
|