优雅的方式只复制对象的一部分 [英] Elegant way to copy only a part of an object

查看:163
本文介绍了优雅的方式只复制对象的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个更大的对象创建一个新对象,只复制它的一些属性。我知道的所有解决方案都不是很优雅,我想知道是否有更好的选择,如果可能的原生(没有其他功能,如下面的代码末尾)?

I would like to create an new object from a bigger one, by copying only a few properties from it. All the solutions I know are not very elegant, I wonder if there is a better choice, native if possible (no additional function like at the end of the following code)?

以下是我现在通常做的事情:

Here is what I usually do for now:

// 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):
let coords3 = {};
for (let attr of ['x','y','z']) coords3[attr] = source[attr];

// Similar to the 3rd method, using a function:
function extract(src, ...props) {
    let obj = {};
    props.map(prop => obj[prop] = src[prop]);
    return obj;
}
let coords4 = extract(source, 'x', 'y', 'z');


推荐答案

一种方法是通过对象解构和箭头函数:

let source = {
    x: 120,
    y: 200,
    z: 150,
    radius: 10,
    color: 'red',
};

let result = (({ x, y, z }) => ({ x, y, z }))(source);

console.log(result);

这种方式的工作原理是箭头函数(({x,y,z})=>({x,y,z}))立即用<$ c $调用c> source 作为参数。它将 source 解构为 x y z ,然后立即将它们作为新对象返回。

The way this works is that the arrow function (({ x, y, z }) => ({ x, y, z })) is immediately called with source as the parameter. It destructures source into x, y, and z, and then immediately returns those as a new object.

这篇关于优雅的方式只复制对象的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆