0

I have an array of objects:

const car = [{
  color: 'blue',
  brand: 'Ford'
},{
  color: 'red',
  brand: 'Chevy'
}]

I'm trying to create a function that will remove a given property. For example, I want to remove the 'color' property from all car objects. If I write the following code it works:

car.forEach(function(v){ delete v.color})

However, if I try to create a function to do this, it doesnt work:

function removeP(arr, keyPar) {
  arr.forEach(function(v){ delete v.keyPar});
}

removeP(car, color)

I've also tried calling the function as:

removeP(car,'color')

which, at least doesnt give me an error, but also doesnt work.

Why isnt this function working?

Brady B
  • 35
  • 3

1 Answers1

0

You should use bracket notation when storing keys in variables:

const car = [{
  color: 'blue',
  brand: 'Ford'
},{
  color: 'red',
  brand: 'Chevy'
}];

function removeP(arr, keyPar) {
  arr.forEach(function(v){ delete v[keyPar]});
}

removeP(car, 'color');

console.log(car);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55