Skip to content
Advertisement

deleting object keys which start with a vowel js

I need to remove all keys, which start with the vowel from an object but I can’t figure out how to do it. This is what I have so far. In this example only the ‘chip’ key should stay and all the others should be removed. Can you guys help me with this?

'use strict'

function removeVowelKeys(object) {
  for (let key in object) {
    if (key[0] === 'a' || key[0] === 'A' || key[0] === 'u' || key[0] === 'U' ||
    key[0] === 'i' || key[0] === 'I' || key[0] === 'o' || key[0] === 'O' ||
    key[0] === 'e' || key[0] === 'E' || key[0] === 'y' || key[0] === 'Y' ) {
      delete object.key
  }
}
}


console.log(removeVowelKeys({
  alarm: 'This is SPARTA!!!',
  chip: 100,
  isValid: false,
  Advice: 'Learn it hard',
  onClick: 'make it great again',
}));

Advertisement

Answer

You need to return your object from your function, but also you shouldn’t delete keys from the object as you’re looping over it.

Something like this will do it:

const removeVowelKeys = (obj) =>
  Object.fromEntries(
    Object.entries(obj).filter(
      ([k]) => !["a", "e", "i", "o", "u"].includes(k.toLowerCase()[0])
     )
  );

console.log(removeVowelKeys({
  alarm: 'This is SPARTA!!!',
  chip: 100,
  isValid: false,
  Advice: 'Learn it hard',
  onClick: 'make it great again',
}));

I also fixed up your original method to copy the object before iterating over it and also using [square bracket] notation to use your keys correctly:

function removeVowelKeys(obj) {
  for (let key in { ...obj }) {
    if (
      key[0] === "a" ||
      key[0] === "A" ||
      key[0] === "u" ||
      key[0] === "U" ||
      key[0] === "i" ||
      key[0] === "I" ||
      key[0] === "o" ||
      key[0] === "O" ||
      key[0] === "e" ||
      key[0] === "E" ||
      key[0] === "y" ||
      key[0] === "Y"
    ) {
      delete obj[key];
    }
  }
  return obj;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement