You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历JavaScript对象并移除非hours、days的属性?

保留指定属性,移除其他对象属性的实现方法

嘿,这个需求其实挺常见的,核心就是只保留hours和days属性,删掉所有其他属性。我给你分享几种实用的实现方式,你可以根据场景选:

方法1:遍历原对象直接删除不需要的属性

适合需要直接修改原对象的场景,用for...in循环遍历所有属性,结合hasOwnProperty避免处理原型链上的属性:

const targetObj = {
  hours: 24,
  days: 7,
  minutes: 1440,
  seconds: 86400,
  weekName: "Sunday"
};

// 定义需要保留的属性列表
const allowedProps = ['hours', 'days'];

// 遍历对象的所有可枚举属性
for (const prop in targetObj) {
  // 仅处理对象自身的属性(排除原型继承的属性)
  if (targetObj.hasOwnProperty(prop)) {
    // 如果属性不在允许列表里,就删除它
    if (!allowedProps.includes(prop)) {
      delete targetObj[prop];
    }
  }
}

console.log(targetObj); // 输出: { hours: 24, days: 7 }

方法2:提取保留属性(不修改原对象,更安全)

如果不想改动原对象,推荐这种方式——直接从原对象中提取需要的属性,生成新对象:

子方法A:解构赋值(最简洁)

const targetObj = {
  hours: 24,
  days: 7,
  minutes: 1440,
  seconds: 86400,
  weekName: "Sunday"
};

// 解构出需要的属性,剩下的用...rest忽略
const { hours, days, ...unusedProps } = targetObj;
const filteredObj = { hours, days };

console.log(filteredObj); // 输出: { hours: 24, days: 7 }
console.log(targetObj); // 原对象完全不变

子方法B:用Object.fromEntries过滤

适合需要动态调整保留属性列表的场景:

const targetObj = {
  hours: 24,
  days: 7,
  minutes: 1440,
  seconds: 86400,
  weekName: "Sunday"
};

const allowedProps = ['hours', 'days'];
const filteredObj = Object.fromEntries(
  // 把对象转成键值对数组,过滤出符合条件的项,再转回对象
  Object.entries(targetObj).filter(([key]) => allowedProps.includes(key))
);

console.log(filteredObj); // 输出: { hours: 24, days: 7 }

方法3:封装成可复用函数

如果需要多次处理这类需求,可以封装成工具函数,支持自定义保留属性:

function filterObjectProps(originalObj, keepProps) {
  // 先浅拷贝原对象,避免修改原数据
  const newObj = { ...originalObj };
  for (const prop in newObj) {
    if (newObj.hasOwnProperty(prop) && !keepProps.includes(prop)) {
      delete newObj[prop];
    }
  }
  return newObj;
}

// 使用示例
const userStats = { hours: 8, days: 5, salary: 8000, role: 'developer' };
const filteredStats = filterObjectProps(userStats, ['hours', 'days']);
console.log(filteredStats); // { hours: 8, days: 5 }
console.log(userStats); // 原对象不受影响

小提醒:如果你的环境不支持Array.includes(比如旧版IE),可以用Array.indexOf(prop) !== -1替代。

内容的提问来源于stack exchange,提问作者docodernew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:59:23