如何编写一个函数,在ES6中以最紧凑的方式只占用少量属性?
我已经提出了使用解构+简化对象文字的解决方案,但我不喜欢在代码中重复的字段列表.
有更薄的解决方案吗?
(v) => {
let { id, title } = v;
return { id, title };
}
Run Code Online (Sandbox Code Playgroud) javascript destructuring ecmascript-harmony ecmascript-6 ecmascript-next
我想通过从中复制一些属性来从较大的对象创建一个新对象.我知道的所有解决方案都不是很优雅,我想知道是否有更好的选择,如果可能的原生(没有像下面代码末尾那样的附加功能)?
这是我现在通常做的事情:
// I want to keep only x, y, and z properties:
let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
// 1st method (not elegant, especially with even more properties):
let coords1 = {
x: source.x,
y: source.y,
z: source.z,
};
// 2nd method (problem: it pollutes the current scope):
let {x, y, z} = source, coords2 = {x, y, z};
// 3rd method (quite hard to read for such simple task): …Run Code Online (Sandbox Code Playgroud)