簡體   English   中英

帶有點符號的Vue JS lodash findKey嵌套object返回未定義

[英]Vue JS lodash findKey nested object with dot notation returns undefined

我正在嘗試從我擁有的某個資格數組中提取嵌套 object 鍵的值,但由於某種原因我得到了一個未定義的值,並且需要知道我缺少什么。

給定以下數組:

const eligibilityCriteria = [
  { field: 'loan.amount', operator: '>=', value: 1000 },
  { field: 'loan.term', operator: '>=', value: 1 },
  { field: 'applicant.birthday', operator: '>=', value: 40 },
  { field: 'applicant.isHomeowner', operator: '==', value: false }
]

我需要從嵌套的 object 中找到loan.amount並提取它的值:

我的大嵌套 object 是(來自商店)

application: {
  meta: {
    brand: '',
    version: '',
    affiliate: '',
    affiliate_full: '',
    campaign: '',
    client_hostname: '',
    client_href: '',
    client_origin: '',
    client_useragent: '',
    client_ip: '127.0.0.1',
    icicle_hash: ''
  },
  loan: {
    amount: 500,
    term: null,
    purpose: null
  }
}

我現在的 function 是:

checkEligibility () {
  const eligibilityCriteria = [
    { field: 'loan.amount', operator: '>=', value: 1000 },
    { field: 'loan.term', operator: '>=', value: 1 },
    { field: 'applicant.birthday', operator: '>=', value: 40 },
    { field: 'applicant.isHomeowner', operator: '==', value: false }
  ]

  for (const [index, offer] of this.datasets.offers.entries()) {
    const eligibility = eligibilityCriteria

    if (eligibility) {
      for (const [ci, criteria] of eligibility.entries()) {

        // TODO: this fails to pull the value, returns undefined
        const field = _.findKey(this.$store.state.application.application, criteria.field)
      }
    }
  }
}

我錯過了什么?

您必須誤解_.findKey()的作用

此方法與 _.find 類似,只是它返回第一個元素謂詞的鍵,而不是元素本身返回真值。

請參見下面代碼中的示例 2

如果要從給定路徑的 object 中檢索值,則必須使用_.property() (下面的示例 2)

 const eligibilityCriteria = [ { field: 'loan.amount', operator: '>=', value: 1000 }, { field: 'loan.term', operator: '>=', value: 1 }, ] const application = { loan: { amount: 500, term: 2, amount2: 0, } } // example 1 // outputs "loan" console.log(_.findKey(application, "amount")) // outputs undefined - there is no key in application object that has property chain "loan.amount" console.log(_.findKey(application, "loan.amount")) // outputs undefined - "amount2" key is there but the value is falsy console.log(_.findKey(application, "amount2")) // example 2 for (const [ci, criteria] of eligibilityCriteria.entries()) { console.log(criteria.field, _.property(criteria.field)(application)) }
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM