3
const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
]

const output = []

Object.keys(cars).map((car) => {
  output.push({
      foo: cars[car].defaultCategory
  })
})

console.log(output)

This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.

So if I replace push argument with

${cars[car].id}`: cars[car].defaultCategory

I get SyntaxError: Unexpected template string

What am I doing wrong?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
knitevision
  • 3,023
  • 6
  • 29
  • 44

2 Answers2

7

Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:

const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
];

const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.

This is how should be your code:

var output = cars.map(function(car) {
  return {
    [car.id]: car.defaultCategory
  };
});

var cars = [{
  'id': 'truck',
  'defaultCategory': 'vehicle'
}];


var output = cars.map(function(car) {
  return {
    [car.id]: car.defaultCategory
  };
});

console.log(output);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78