Add transform

This commit is contained in:
2026-01-16 14:17:19 +01:00
parent cf7fa50e82
commit 6be4d378f3
2 changed files with 50 additions and 1 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tp/helpers", "name": "@tp/helpers",
"version": "2.10.3", "version": "2.11.0",
"description": "", "description": "",
"main": "closest.js", "main": "closest.js",
"scripts": { "scripts": {

49
transform.js Normal file
View File

@@ -0,0 +1,49 @@
import { reach } from './reach.js';
/**
* Transform an object or collection to a different form.
*
* @param {Object} source The object to transform.
* @param {Object} map Object that describes how to transform the source: { [path.in.transformed.object]: [path.in.source] }.
* @return {Object} A new object with the new structure.
*/
export const transform = (source, map) => {
const sep = '.';
if (Array.isArray(source)) {
const results = [];
for (let i = 0; i < source.length; ++i) {
results.push(transform(source[i], map));
}
return results;
}
const result = {};
const keys = Object.keys(map);
for (let i = 0, li = keys.length; i < li; ++i) {
const key = keys[i];
const path = key.split(sep);
const srcPath = map[key];
if (typeof srcPath !== 'string') {
console.warn('Transformation path invalid. Skipping.');
continue;
}
let segment;
let res = result;
while (path.length > 1) {
segment = path.shift();
if (!res[segment]) {
res[segment] = {};
}
res = res[segment];
}
segment = path.shift();
res[segment] = reach(srcPath, source);
}
return result;
}