Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Dynamically generated object key [duplicate]

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?

like image 641
knitevision Avatar asked Aug 04 '26 09:08

knitevision


2 Answers

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);
like image 185
Ori Drori Avatar answered Aug 05 '26 23:08

Ori Drori


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);
like image 35
cнŝdk Avatar answered Aug 05 '26 21:08

cнŝdk