是否有惯用的 Javascript 方法来避免为失败的 `Array.find()` 提供默认值?
Is there an idiomatic Javascript way of avoiding providing a default value for a failing `Array.find()`?
我有动态创建对象的工作代码:
// dummy sources
const departments = [
{ code: 'DA', title: 'Department A' },
{ code: 'DB', title: 'Department B' },
{ code: 'DC', title: 'Department C' },
{ code: 'DD', title: 'Department D' },
]
const reviewers = ['Department A','Pub Lunches','Department C','Department D']
const validationObject = {}
// actual code
reviewers.forEach( (reviewer, index) => {
const dept = departments.find( dept => dept.title === reviewer) || { code: reviewer.replace(/[ ]/g, '_').replace(/[/W]/g, '') }
validationObject[dept.code.toLowerCase()+'_reviewer'] = {blah:'blah'}
})
console.log(validationObject)
它有效,但是创建一个虚拟对象只是为了在抓取未定义结果的 code
元素时(当部门中没有匹配元素时)克服错误看起来很尴尬。
是否有我缺少的更惯用的方法?
在 ES6 中应该是这样的
const dept = {
code: reviewer.replace(/[ ]/g, '_').replace(/[/W]/g, ''),
...departments.find( dept => dept.title === reviewer)
}
如果您不介意使用来自 lodash 的外部库 get()
将阻止您创建不必要的对象,同时将对您进行属性验证有很大帮助:
const { get } = require('lodash')
const backupCode = reviewer.replace(/[ ]/g, '_').replace(/[/W]/g, '').toLowerCase() + '_reviewer';
const key = get(departments.find( dept => dept.title === reviewer), 'code', backupCode)
validationObject[key] = {}
否则你可以使用展开运算符。
我有动态创建对象的工作代码:
// dummy sources
const departments = [
{ code: 'DA', title: 'Department A' },
{ code: 'DB', title: 'Department B' },
{ code: 'DC', title: 'Department C' },
{ code: 'DD', title: 'Department D' },
]
const reviewers = ['Department A','Pub Lunches','Department C','Department D']
const validationObject = {}
// actual code
reviewers.forEach( (reviewer, index) => {
const dept = departments.find( dept => dept.title === reviewer) || { code: reviewer.replace(/[ ]/g, '_').replace(/[/W]/g, '') }
validationObject[dept.code.toLowerCase()+'_reviewer'] = {blah:'blah'}
})
console.log(validationObject)
它有效,但是创建一个虚拟对象只是为了在抓取未定义结果的 code
元素时(当部门中没有匹配元素时)克服错误看起来很尴尬。
是否有我缺少的更惯用的方法?
在 ES6 中应该是这样的
const dept = {
code: reviewer.replace(/[ ]/g, '_').replace(/[/W]/g, ''),
...departments.find( dept => dept.title === reviewer)
}
如果您不介意使用来自 lodash 的外部库 get()
将阻止您创建不必要的对象,同时将对您进行属性验证有很大帮助:
const { get } = require('lodash')
const backupCode = reviewer.replace(/[ ]/g, '_').replace(/[/W]/g, '').toLowerCase() + '_reviewer';
const key = get(departments.find( dept => dept.title === reviewer), 'code', backupCode)
validationObject[key] = {}
否则你可以使用展开运算符。