删除以元音js开头的对象键

我需要删除所有以对象中的元音开头的键,但我不知道该怎么做。这是我到目前为止所拥有的。在此示例中,仅应保留“芯片”密钥,而应删除所有其他密钥。你们能帮我解决这个问题吗?


'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',

}));


哈士奇WWW
浏览 117回答 2
2回答

牧羊人nacy

您需要从函数返回对象,但也不应该在循环对象时从对象中删除键。像这样的事情会做到这一点: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',}));我还修复了您的原始方法以在迭代对象之前复制对象,并使用[square bracket]符号来正确使用您的键: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;}

拉莫斯之舞

我是这样做的。确保您实际上从函数中返回了一些内容...另请注意,y 在技术上不是元音。function removeVowelKeys(obj) {    let output = {};    for (let key in obj) {        if (!(['a', 'e', 'i', 'o', 'u'].includes(key[0].toLowerCase()))) output[key] = obj[key];    }    return output;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript