优雅的方式只复制对象的一部分

yol*_*yer 6 javascript javascript-objects

我想通过从中复制一些属性来从较大的对象创建一个新对象.我知道的所有解决方案都不是很优雅,我想知道是否有更好的选择,如果可能的原生(没有像下面代码末尾那样的附加功能)?

这是我现在通常做的事情:

// 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');
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 14

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

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

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

console.log(result);
Run Code Online (Sandbox Code Playgroud)

这种方式的工作方式(({ x, y, z }) => ({ x, y, z }))是立即调用箭头函数source作为参数.它将析构source化为x,yz,然后立即将它们作为新对象返回.


Vik*_*ngh 6

您可以通过Spread Operator执行如下操作

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

let {radius, color, ...newObj} = source;
console.log(newObj);
Run Code Online (Sandbox Code Playgroud)

  • 这是“省略”而不是“选择”:) (2认同)

Nin*_*olz 5

只需要一个功能.

const extract = ({ x, y, z }) => ({ x, y, z });

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

console.log(extract(source));
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用目标属性对目标对象进行解构.

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

({ x: target.x, y: target.y, z: target.z } = source);

console.log(target);
Run Code Online (Sandbox Code Playgroud)