0

I have got an object:

blocks: [
  {
    type: 'animal',
    data: { text: 'Bark bark' }
  },
  {
    type: 'human',
    data: { text: 'Speak speak' }
  },
  ...
]

The data: naming does not fit my needs and I would like to rename it with the type value. So It should look like this:

blocks: [
  {
    type: 'animal',
    animal: { text: 'Bark bark' }
  },
  {
    type: 'human',
    human: { text: 'Speak speak' }
  },
  ...
]

How can I achieve this with very little code of javascript? My solution does work but seems to be stupid (especially if you consider 10+ different kind of types):

const blocks = [];
oldBlocks.map(block => {
    const {type, data} = block;
    blocks.push({
        type: type,
        animal: type === "animal" ? data : undefined,
        human: type === "human" ? data : undefined,
        ....
    });
});
Marian Rick
  • 3,350
  • 4
  • 31
  • 67
  • @sideshowbarker you are right, this is somehow a duplicate and I found the linked thread, but I was not able to understand it. Luckily zfrisch nailed it down to the most simple example :-) – Marian Rick Aug 15 '19 at 22:41

2 Answers2

2

Use brackets to denote an expression inside of an object, allowing you to evaluate variables as key names:

blocks.map(({type, data}) => ({ type, [type]: data }));

Example:

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);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
1

A possible Solution:

for i in blocks:
i["'"+i[type]+"'"]=i['data']
delete(i['data'])