从 JavaScript 对象中删除数字属性

javascriptweb developmentobject oriented programming更新于 2025/9/26 4:28:17

我们得到一个包含一些随机属性的对象,包括一些数字、布尔值、字符串和对象本身。

我们需要编写一个函数,该函数将对象作为第一个参数,将字符串作为第二个参数,第二个参数的可能值是 JavaScript 中任何数据类型的名称,如数字、字符串、对象、布尔值、符号等。

我们的任务是删除第二个参数指定的每个类型的属性。如果没有提供第二个参数,则默认使用"数字"。

执行此操作的完整代码如下 −

const obj = {
   name: 'Lokesh Rahul',
   age: 29,
   mother: 'Avantika Rahul',
   father: 'Trilok Rahul',
   matches: 123,
   average: 45.23,
   isFit: true,
   runs: {
      odi: 5674,
      test: 3456
   }
};
const shedData = (obj, type = 'number') => {
   for(const key in obj){
      if(typeof obj[key] === type){
         delete obj[key];
      };
   };
};
shedData(obj, 'string');
console.log(obj);

输出

控制台中的输出将是 −

{
   age: 29,
   matches: 123,
   average: 45.23,
   isFit: true,
   runs: { odi: 5674, test: 3456 }
}

相关文章


有用资源