Javascript 根据抛出未定义的方案查找和映射值

Javascript find and map values based on scheme throwing undefined

我正在与 Javascript 合作构建一个映射函数,给定一个方案应该在 application 变量中找到映射器对象的值。

我这样做的尝试导致了一个未定义的错误,我试图弄清楚我需要更改什么才能使其正常工作,我已经整理了一个可以找到的 JS fiddle here 还有。

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 对象包含一些 key/value 对,这是我想尝试在 application 中找到的值。例如,我的控制台日志应该检索如下内容:

它们可能并不总是按此顺序排列,因此我需要 (在映射器的每次迭代中) 在我的 application 变量中找到键。

我需要在这里更改什么?

'outgoings.food' 之类的字符串对于导航数据结构无效。你可以使用一些“lenses”库或者写这样的东西......

const mapper = {
  "AppFoodSpend": ["outgoings", "food"],
  "AppCreditSpend": ["outgoings", "credit"]
}

for (const field in mapper) {
    console.log(
        mapper[field].reduce(
            (ctx, path) => ctx[path],
            application.state
        )
    )
}