object-path-resolver
Version:
A simple object path resolver
76 lines • 3.43 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.syncGetValueFromObjWithPath = exports.getValueFromObjWithPath = void 0;
const convert_path_to_array_of_keys_1 = require("./convert-path-to-array-of-keys");
const protoKeys = new Set(['prototype', '__proto__']);
async function getValueFromObjWithPath(obj, keys, options) {
let currentObj = obj;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (currentObj == undefined && i !== keys.length - 1) {
return options.missing;
}
if (key === convert_path_to_array_of_keys_1.kAllItems) {
if (Array.isArray(currentObj)) {
const leftKeys = keys.slice(i + 1);
return Promise.all(currentObj.map((item) => getValueFromObjWithPath(item, leftKeys, options)));
}
if (typeof currentObj[Symbol.iterator] === 'function') {
const leftKeys = keys.slice(i + 1);
return Promise.all(Array.from(currentObj).map((item) => getValueFromObjWithPath(item, leftKeys, options)));
}
return options.missing;
}
if ((typeof currentObj !== 'object' && typeof currentObj !== 'function') || currentObj === null) {
return options.missing;
}
if (key !== 'prototype' && !(key in currentObj)) {
return options.missing;
}
if (protoKeys.has(key) && !options.allowPrototypeAccess) {
throw new Error(`using ${key} is not allowed, you can enable it by passing allowPrototypeAccess: true`);
}
currentObj = currentObj[key];
if (typeof currentObj === 'function') {
currentObj = await currentObj();
}
}
return currentObj;
}
exports.getValueFromObjWithPath = getValueFromObjWithPath;
function syncGetValueFromObjWithPath(obj, keys, options) {
let currentObj = obj;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (currentObj == undefined && i !== keys.length - 1) {
return options.missing;
}
if (key === convert_path_to_array_of_keys_1.kAllItems) {
if (Array.isArray(currentObj)) {
const leftKeys = keys.slice(i + 1);
return currentObj.map((item) => syncGetValueFromObjWithPath(item, leftKeys, options));
}
if (typeof currentObj[Symbol.iterator] === 'function') {
const leftKeys = keys.slice(i + 1);
return Array.from(currentObj).map((item) => syncGetValueFromObjWithPath(item, leftKeys, options));
}
return options.missing;
}
if ((typeof currentObj !== 'object' && typeof currentObj !== 'function') || currentObj === null) {
return options.missing;
}
if (key !== 'prototype' && !(key in currentObj)) {
return options.missing;
}
if (protoKeys.has(key) && !options.allowPrototypeAccess) {
throw new Error(`using ${key} is not allowed, you can enable it by passing allowPrototypeAccess: true`);
}
currentObj = currentObj[key];
if (typeof currentObj === 'function') {
currentObj = currentObj();
}
}
return currentObj;
}
exports.syncGetValueFromObjWithPath = syncGetValueFromObjWithPath;
//# sourceMappingURL=get-value-from-obj-with-path.js.map
;