JavaScript-数组,对象-如何精简此代码

时间:2019-01-25 06:28:57

标签: javascript arrays ecmascript-6 javascript-objects

如何简化此代码? 我认为这可能是重构的更好方法。

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]

2 个答案:

答案 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);