当名称路径存储在未知长度的数组中时,如何从多维对象中获取值



我正在创建一个文件夹目录,需要允许用户在其中导航。我有一个全局变量,用于存储用户在该目录中的位置。如何访问他们所选文件夹中的内容。

这就是我所做的。

let location = ["2022","March","Week4"];
let content = folderInformation["2022"]["March"]["Week4"];

然而,文件名";2022年3月,第4周等;由用户设置。

所以我可以这么做。

let location = ["2022","March","Week4"];
let layer1 = location[0];
let layer2 = location[1];
let layer3 = location[2];
let content = folderInformation[layer1][layer2][layer3];

然而,用户可以是2层深或15层。

我试过

let layers = location.join("][");
let content = folderInformation[layers];

let layers = "["+location.join("][")+"]";
let content = folderInformation+layers;

没有成功。访问对象中内容的最佳选项是什么?

带有reduce:的短版本

const content = location.reduce((o,l)=>o?.[l],folderinformation);

循环遍历locations数组,并逐个访问folderInformation对象中的每个位置。这样,每次迭代都会深入一个层次。

function getFolderInformation(folderInformation, locations) {
let currentLocation = folderInformation;

for (const location of locations) {
if (location in currentLocation) {
currentLocation = currentLocation[location];
}
}

return currentLocation;
}
const folderInformation = {
'2022': {
'Februari': {
'Week1': {
title: 'Nope',
description: 'Not this one'
}
},
'March': {
'Week3': {
title: 'Also no',
description: 'Wrong'
},
'Week4': {
title: 'Foo',
description: 'Bar'
},
}
}
};
let locations = ["2022", "March", "Week4"];
let content = getFolderInformation(folderInformation, locations);
console.log(content);

最新更新