Ниже приведен метод получения свойства или вложенного объекта из объекта с использованием нотации пути. Это адаптация аналогичного вопроса, заданного «Prusprus» в 2014 году.
У меня есть файл конфигурации с вложенными массивами и вы хотите получить доступ к данным с веб-страницы, отправив путь в form:
"unit_cfg [2] .chn_cfg [7] .chn_type"
Эта функция вернет одно свойство или объект. Да, это можно упростить ...
function fetchFromObject(obj: Object, path: string): boolean | Object {
var dot_idx: number;
var lbkt_idx: number;
var rbkt_idx: number;
var prop: string;
var prop_idx: number;
var new_obj: Object;
var new_path: string;
// Return if no object.
if (typeof obj === 'undefined') {
return false;
}
// Get index of first left bracket in path.
lbkt_idx = path.indexOf('[');
// If left bracket.
if (lbkt_idx > -1) {
// Get right bracket index.
rbkt_idx = path.indexOf(']');
}
// Get index of first dot in path.
dot_idx = path.indexOf('.');
/*
* Most complicated situation is if there are both brackets
* and dots in the path. This means we have a mixture of both
* indexed and non-indexed properties:
*
* x[].y --or-- x.y[]
*
* In this case, we must see if the indexed property is before
* or after the non-indexed property.
*
* In either case, we must recurse.
*/
if ((lbkt_idx > -1) && (dot_idx > -1)) {
// If bracket is before dot: x[].y
if (lbkt_idx < dot_idx) {
// Get property string.
prop = path.substr(0, lbkt_idx);
// Get index.
prop_idx = Number(path.substring(lbkt_idx + 1, rbkt_idx));
// Get path to right of dot.
new_path = path.substr(dot_idx + 1);
// Get new object.
new_obj = obj[prop][prop_idx];
// Recurse.
return fetchFromObject(new_obj, new_path);
}
// Else dot before bracket: x.y[]
else {
// Get property string.
prop = path.substr(0, dot_idx);
// Get path to right of dot.
new_path = path.substr(dot_idx + 1);
// Get new object.
new_obj = obj[prop];
// Recurse.
return fetchFromObject(new_obj, new_path);
}
}
/*
* Else recurse if dotted property; x.y
*/
else if (dot_idx > -1) {
// Get property string.
prop = path.substr(0, dot_idx);
// Get path to right of dot.
new_path = path.substr(dot_idx + 1);
// Get new object.
new_obj = obj[prop];
// Recurse.
return fetchFromObject(new_obj, new_path);
}
/*
* Else done if single indexed property: x[]
*/
else if (lbkt_idx > -1) {
// Get property string.
prop = path.substr(0, lbkt_idx);
// Get index.
prop_idx = Number(path.substring(lbkt_idx + 1, rbkt_idx));
// Return with object.
return obj[prop][prop_idx];
}
/*
* Else single non-indexed property.
*/
return obj[path];
}