我正在使用 Javascript 來構建一個映射函式,給定一個方案,應該在一個application變數中找到映射器物件的值。
我嘗試這樣做會導致一個未定義的錯誤,我試圖弄清楚我需要更改什么才能使其正常作業,我已經整理了一個 JS 小提琴,也可以在這里找到。
const application = {
state: {
outgoings: {
credit: 0,
food: 0
}
}
}
const mapper = {
"AppFoodSpend": "outgoings.food",
"AppCreditSpend": "outgoings.credit"
}
for (const field in mapper) {
console.log(application.state[mapper[field]])
// expected results should be credit 0 and food 0
}
對于進一步的背景關系,我有一個名為的物件application,其中包含一些欄位,它們的順序可能并不總是相同。我的mapper物件包含一些鍵/值對,這是我想在application. 例如,我的控制臺日志應該檢索如下內容:
application.state.outgoings.foodapplication.state.outgoings.credit
它們可能并不總是按此順序排列,因此我需要(在映射器的每次迭代中)在我的application變數中找到鍵。
我需要在這里更改什么?
uj5u.com熱心網友回復:
像 'outgoings.food' 這樣的字串對于導航資料結構是無效的。你可以使用一些“鏡頭”庫或寫這樣的東西......
const mapper = {
"AppFoodSpend": ["outgoings", "food"],
"AppCreditSpend": ["outgoings", "credit"]
}
for (const field in mapper) {
console.log(
mapper[field].reduce(
(ctx, path) => ctx[path],
application.state
)
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361224.html
標籤:javascript 数组 目的 ecmascript-6
下一篇:物件(可選任何):獲取元素
