[英]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.