使用动态变量访问 javascript 对象中的第 n 级嵌套属性
Access nth level nested attribute in javascript object using dynamic variable
假设我有一个对象
const aggs = {
cat.id: {
terms: { field: 'cat.id', size: 10 },
aggs: { cat.label: {field: 'cat.label', size: 5} }
}
}
在动态变量中我有
const key = '[cat.id].aggs'
现在我需要使用动态变量访问 aggs 对象中的属性 aggs
aggs[key]
这不起作用,如何动态访问嵌套属性?显然像这样直接访问它是可行的
aggs['cat.id'].aggs
您可以使用 usual solutions,但使用适当处理括号的特定正则表达式,允许 属性 名称中的点:
const pathToArray = path =>
Array.from(path.matchAll(/\[(.*?)\]|[^.[]+/g) || [],
([prop, inbrackets]) => inbrackets || prop);
function deepGet(obj, path, defaultVal = null) {
for (let prop of pathToArray(path)) {
if (!(prop in obj)) return defaultVal;
obj = obj[prop];
}
return obj;
}
function deepSet(obj, path, value) {
let arr = pathToArray(path);
arr.slice(0, -1).reduce((a, c, i) =>
Object(a[c]) === a[c] ? a[c] :
a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {},
obj)[arr[arr.length - 1]] = value;
return obj;
}
// Your example:
const aggs = {"cat.id": {terms: {field: "cat.id",size: 10},aggs: {"cat.label": {field: "cat.label",size: 5}}}};
const key = "[cat.id].aggs";
console.log(deepGet(aggs, key));
deepSet(aggs, key, "hello");
console.log(deepGet(aggs, key));
假设我有一个对象
const aggs = {
cat.id: {
terms: { field: 'cat.id', size: 10 },
aggs: { cat.label: {field: 'cat.label', size: 5} }
}
}
在动态变量中我有
const key = '[cat.id].aggs'
现在我需要使用动态变量访问 aggs 对象中的属性 aggs
aggs[key]
这不起作用,如何动态访问嵌套属性?显然像这样直接访问它是可行的
aggs['cat.id'].aggs
您可以使用 usual solutions,但使用适当处理括号的特定正则表达式,允许 属性 名称中的点:
const pathToArray = path =>
Array.from(path.matchAll(/\[(.*?)\]|[^.[]+/g) || [],
([prop, inbrackets]) => inbrackets || prop);
function deepGet(obj, path, defaultVal = null) {
for (let prop of pathToArray(path)) {
if (!(prop in obj)) return defaultVal;
obj = obj[prop];
}
return obj;
}
function deepSet(obj, path, value) {
let arr = pathToArray(path);
arr.slice(0, -1).reduce((a, c, i) =>
Object(a[c]) === a[c] ? a[c] :
a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {},
obj)[arr[arr.length - 1]] = value;
return obj;
}
// Your example:
const aggs = {"cat.id": {terms: {field: "cat.id",size: 10},aggs: {"cat.label": {field: "cat.label",size: 5}}}};
const key = "[cat.id].aggs";
console.log(deepGet(aggs, key));
deepSet(aggs, key, "hello");
console.log(deepGet(aggs, key));