我正在創建一個檔案夾目錄,需要允許用戶在其中導航。我有一個全域變數,將它們的位置存盤在目錄中。如何訪問他們選擇的檔案夾中的內容。
這就是我什么。
let location = ["2022","March","Week4"];
let content = folderInformation["2022"]["March"]["Week4"];
但是,檔案名“2022, March, Week4, ect”是由用戶設定的。
所以我可以做到這一點。
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;
沒有成功。訪問物件內的內容的最佳選擇是什么?
uj5u.com熱心網友回復:
一個帶有 reduce 的簡短版本:
const content = location.reduce((o,l)=>o?.[l],folderinformation);
uj5u.com熱心網友回復:
遍歷您的陣列并逐個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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447638.html
標籤:javascript 目的
