gpt4 book ai didi

javascript - 仅复制对象的一部分的优雅方式

转载 作者:数据小太阳 更新时间:2023-10-29 05:40:38 26 4
gpt4 key购买 nike

<分区>

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

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

// 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');

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com