destructer-js
Version:
Type-safe utility for dynamic object destructuring
24 lines (23 loc) • 779 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.destruct = destruct;
function destruct(obj, map) {
const getValue = (path, fallback = undefined) => {
var _a;
return (_a = path.split('.').reduce((acc, key) => {
return acc && acc[key] !== undefined ? acc[key] : undefined;
}, obj)) !== null && _a !== void 0 ? _a : fallback;
};
const result = {};
for (const key in map) {
const pathValue = map[key];
if (typeof pathValue === 'string') {
result[key] = getValue(pathValue);
}
else if (Array.isArray(pathValue)) {
const [path, fallback] = pathValue;
result[key] = getValue(path, fallback);
}
}
return result;
}