-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
  • 4,365
  • 11
  • 63
  • 122

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
  • 191,408
  • 23
  • 240
  • 301
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
  • 66,969
  • 9
  • 47
  • 59