JavaScript ES6:如何提取对象属性到新对象且避免键名重复?
问题描述
我想要创建一个新对象savedStyle,从style对象中获取对应的键值对,但不想重复书写对象的键名:
const style = getComputedStyle(document.body); const savedStyle = { position: style.position, // 此处存在键名重复 };
这种重复写法并不理想,一旦出现拼写错误(比如写成psition),会导致代码运行异常,例如执行Object.assign(document.body, savedStyle)时出错。
请问有没有办法可以提取多个值,且保持与原对象相同的键名?
补充说明:目前已知的繁琐写法如下:
const { position } = style; const savedStyle = { position, };
解决方案
1. 解构赋值直接构建对象
通过解构赋值先提取所需属性,再利用对象字面量的简写语法生成目标对象,避免重复键名:
const style = getComputedStyle(document.body); // 提取单个属性 const { position } = style; const savedStyle = { position }; // 提取多个属性 const { position, top, left } = style; const savedStyle = { position, top, left };
如果不需要保留单独的属性变量,也可以用立即执行函数实现一行写法:
const savedStyle = (({ position, top, left }) => ({ position, top, left }))(style);
2. 编写通用工具函数批量提取
如果需要频繁从对象中提取指定键值对,写一个工具函数会更高效,彻底避免键名重复:
function pick(obj, ...keys) { return keys.reduce((result, key) => { if (key in obj) { result[key] = obj[key]; } return result; }, {}); } // 使用示例:提取多个样式属性 const style = getComputedStyle(document.body); const savedStyle = pick(style, 'position', 'top', 'backgroundColor', 'fontSize');
这个函数支持传入任意数量的键名,自动从原对象中提取对应键值对并返回新对象。
3. 解构+扩展运算符(适用于排除少数属性的场景)
如果只需要排除原对象中的少数属性,保留其余属性,可以用解构结合扩展运算符:
const style = getComputedStyle(document.body); // 排除不需要的属性,剩余属性存入savedStyle const { cssText, length, ...savedStyle } = style;
注意:这种方式适合保留大部分属性的场景,若仅需提取特定几个属性,前两种方法更精准。
内容的提问来源于stack exchange,提问作者gremo
相关产品推荐
相关产品推荐

