-2

I have an object which basically consists of some of the names of cars. I just want to delete the key of that object based on user input.

For instance:

let cars = {
  car1: 'BMW',
  car2: 'Lambo',
  car3: 'Mercedes'
};

const deleteCar = (car) => {
  delete cars.car;
}

deleteCar('car1');
console.log(cars);

As you can see, it doesn't actually delete the key from the object. How can I do this?

Axel
  • 2,577
  • 8
  • 37
  • 85

2 Answers2

1

foo.bar in JavaScript is equivalent to foo["bar"]. Thus, if car is a string, delete cars[car] does the correct thing (while delete cars.car tries to delete the literal key "car", which you don't have).

Amadan
  • 179,482
  • 20
  • 216
  • 275
1

Use bracket ([]) notation which allows us to dynamically access property names:

let cars = {
  car1: 'BMW',
  car2: 'Lambo',
  car3: 'Mercedes'
};

const deleteCar = (car) => {
  delete cars[car];
}

deleteCar('car1');
console.log(cars);
Mamun
  • 62,450
  • 9
  • 45
  • 52