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

JavaScript中使用...rest进行对象解构能否支持动态非剩余键?

动态过滤对象键值(替代硬编码解构)

给定对象:

const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };

我们可以通过硬编码解构的方式过滤掉指定键,得到剩余键值组成的对象:

const { key1, key2, ...rest } = obj;

此时rest的值为 { key3: "value3", key4: "value4" }。

但如果要过滤的键是运行时才能确定的数组(比如unwantedKeys),没法提前硬编码,该怎么实现同样的过滤效果?


方法1:用Object.entries + Object.fromEntries过滤

这是最直观简洁的写法,把对象转成键值对数组后过滤掉不需要的键,再转回对象:

const unwantedKeys = ['key1', 'key2']; // 运行时确定的数组
const filteredObj = Object.fromEntries(
  Object.entries(obj).filter(([key]) => !unwantedKeys.includes(key))
);

该方法需要ES2019及以上支持,大部分现代浏览器和Node.js环境都兼容。

方法2:用reduce构建新对象

兼容性更广(支持ES6及以上),手动遍历键值对来构建结果对象:

const unwantedKeys = ['key1', 'key2'];
const filteredObj = Object.keys(obj).reduce((acc, key) => {
  if (!unwantedKeys.includes(key)) {
    acc[key] = obj[key];
  }
  return acc;
}, {});

如果unwantedKeys数组元素较多,建议先转成Set来提升查找效率——因为Set.has()是O(1)时间复杂度,比数组includes()的O(n)快得多:

const unwantedKeysSet = new Set(unwantedKeys);
const filteredObj = Object.keys(obj).reduce((acc, key) => {
  if (!unwantedKeysSet.has(key)) {
    acc[key] = obj[key];
  }
  return acc;
}, {});

方法3:动态解构(不推荐)

虽然能通过动态生成解构语法实现,但需要用到Function构造函数或eval,存在安全风险且可读性差,除非特殊场景否则不建议使用:

const unwantedKeys = ['key1', 'key2'];
const destructCode = `const { ${unwantedKeys.join(', ')}, ...rest } = obj; return rest;`;
const filteredObj = new Function('obj', destructCode)(obj);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:37:21