我有一个对象:
blocks: [
{
type: 'animal',
data: { text: 'Bark bark' }
},
{
type: 'human',
data: { text: 'Speak speak' }
},
...
]
该data:
命名不适合我的需要,我想将它与重命名type
值。所以它应该看起来像这样:
blocks: [
{
type: 'animal',
animal: { text: 'Bark bark' }
},
{
type: 'human',
human: { text: 'Speak speak' }
},
...
]
如何用很少的javascript代码实现这一目标?我的解决方案确实有效,但似乎很愚蠢(特别是如果您考虑10种以上不同类型的类型):
const blocks = [];
oldBlocks.map(block => {
const {type, data} = block;
blocks.push({
type: type,
animal: type === "animal" ? data : undefined,
human: type === "human" ? data : undefined,
....
});
});
使用方括号表示对象内部的表达式,使您可以将变量作为键名求值:
blocks.map(({type, data}) => ({ type, [type]: data }));
let blocks = [
{
type: 'animal',
data: { text: 'Bark bark' }
},
{
type: 'human',
data: { text: 'Speak speak' }
}
],
result = blocks.map(({type, data}) => ({ type, [type]: data }));
console.log(result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句