我有用于动态创建对象的工作代码:
// 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) }
也许在分配前使用dept
运算符检查if
的值:
reviewers.forEach( (reviewer, index) => {
const dept = departments.find( dept => dept.title === reviewer);
if (dept)
validationObject[dept.code.toLowerCase()+'_reviewer'] = {blah:'blah'}
})
或一种解决方案,但使用了额外的内存:
const unique = new Map(departments.map(s => [s.title, s.code]));
reviewers.forEach( (reviewer, index) => {
unique.get(reviewer) ? validationObject[unique.get(reviewer)] = {blah:'blah'} : '';
})
console.log(validationObject)
示例:
// 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 = {}
const unique = new Map(departments.map(s => [s.title, s.code]));
reviewers.forEach( (reviewer, index) => {
unique.get(reviewer) ? validationObject[unique.get(reviewer).toLowerCase()+'_reviewer'] = {blah:'blah'} : '';
})
console.log(validationObject)
真诚地,我猜是打字稿。 https://www.typescriptlang.org/