Adding to an array of objects

PHOTO EMBED

Thu Jun 17 2021 11:00:23 GMT+0000 (Coordinated Universal Time)

Saved by @hisam #javascript #objects #arrays

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
  },
  {
    ...
  },
  ...
]

// add to the beginning 
const car = {
  "color": "red",
  "type": "cabrio",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.unshift(car);

// add to the end
const car = {
 "color": "red",
 "type": "cabrio",
 "registration": new Date('2016-05-02'),
 "capacity": 2
}
cars.push(car);

// add somewhere in the middle 
Array.splice(
  {index where to start},
  {how many items to remove},
  {items to add}
);

// place the car after the 4th element in the array
let car = {
  "color": "red",
  "type": "cabrio",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.splice(4, 0, car);
content_copyCOPY