如何简化此代码? 我认为这可能是重构的更好方法。
const aa = ['red', 'yellow', 'blue']
const bb = { first: 0, second: 1, third: 2 }
const cc = { ...bb }
cc.first = aa[cc.first]
cc.second = aa[cc.second]
cc.third = aa[cc.third]
答案 0 :(得分:0)
在从aa或bb中添加或删除项目后,此解决方案仍然有效,而无需更改代码。
const aa = ['red', 'yellow', 'blue']
const bb = { first: 0, second: 1, third: 2 }
const cc = {};
for(var key in bb)
cc[key] = aa[bb[key]];
答案 1 :(得分:0)
您可以使用.reduce()
和Object.entries()
方法:
const aa = ['red', 'yellow', 'blue']
const bb = { first: 0, second: 1, third: 2 }
const cc = Object.entries(bb)
.reduce((r, [k, i]) => (r[k] = aa[i], r), {});
console.log(cc);