return-tree-objects-path
Version:
A utility to recursively find paths in a list of objects
50 lines (49 loc) • 2.2 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.returnTreeObjectsPath = void 0;
/**
* Recursively finds paths in a list of objects based on a specified target key and value.
*
* @export
* @template T
* @param {T[]} objects - An array of objects to search through.
* @param {keyof T} targetKey - The key to search for in the objects.
* @param {string | number | boolean} targetValue - The value to find in the objects based on the target key.
* @param {keyof T} childrenProperty - The property name representing the children of each object.
* @returns {Omit<T, typeof childrenProperty>[]} An array of objects representing the path from the root to the target.
*/
function returnTreeObjectsPath(objects, targetKey, targetValue, childrenProperty) {
var result = [];
function findRecursively(obj) {
if (obj[targetKey] === targetValue) {
var _a = obj, _b = childrenProperty, _ = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
result.unshift(rest);
return true;
}
if (obj[childrenProperty] && Array.isArray(obj[childrenProperty])) {
for (var _i = 0, _c = obj[childrenProperty]; _i < _c.length; _i++) {
var child = _c[_i];
if (findRecursively(child)) {
var _d = obj, _e = childrenProperty, _ = _d[_e], rest = __rest(_d, [typeof _e === "symbol" ? _e : _e + ""]);
result.unshift(rest);
return true;
}
}
}
return false;
}
objects.some(findRecursively);
return result;
}
exports.returnTreeObjectsPath = returnTreeObjectsPath;
;