Search code examples
javascriptjavascript-objects

Is there a more compact way to declare an array of objects?


I'm a C# developer who uses JavaScript when I need to.

Is there a more compact way to write the following? Is it necessary to repeat the name of every member for each item?

let cars = [
  {
    "color": "purple",
    "type": "minivan",
    "registration": new Date('2017-01-03'),
    "capacity": 7
  },
  {
    "color": "red",
    "type": "station wagon",
    "registration": new Date('2018-03-03'),
    "capacity": 5
  },
  {
    ...
  },
]

Solution

  • Can you using a factory function:

    function createCar(color, type, registration, capacity) {
      return {
        color,
        type,
        registration: new Date(registration),
        capacity,
      };
    }
    let cars = [
      createCar("purple", "minivan", "2017-01-03", 7),
      createCar("red", "station wagon", "2018-03-03", 5),
    ];