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



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

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

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

其工作方式是以source为参数立即调用箭头函数(({ x, y, z }) => ({ x, y, z }))。它将source分解为xyz,然后立即将它们作为新对象返回。

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

let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
let {radius, color, ...newObj} = source;
console.log(newObj);

只需要一个函数。

const extract = ({ x, y, z }) => ({ x, y, z });
let source = { x: 120, y: 200, z: 150, radius: 10, color: 'red' };
console.log(extract(source));

另一种解决方案是对具有目标属性的目标对象进行破坏。

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

1st方法优雅且可读。

请不要用一些变通方法混淆简单的操作。其他需要维护这个代码的人,包括未来的自己,将来都会非常感激。

IIFE是否具有析构函数?:

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

对于像这样的简单情况,其他答案中提到的对象析构函数非常简洁,但在处理更大的结构时,当您加倍使用属性名称时,往往会显得有点麻烦。

扩展你自己的答案——如果你要写一个extract实用程序(我会自己滚动以获得乐趣(。。。您可以通过对其进行currying使其更加灵活,允许您交换参数的顺序(尤其是将数据源放在最后(,同时在接受属性名称时仍然是可变的。

我认为这个签名:extract = (...props) => src => { ... }更优雅,因为它在编写新的命名函数时允许更大程度的重用:

const extract = (...props) => src => 
Object.entries(src).reduce(
(obj, [key, val]) => (
props.includes(key) && (obj[key] = val), 
obj
), {})
const getCoords = extract('x', 'y', 'z')
const source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red'
}
console.log(getCoords(source))

您可以在[x,y,z]数组上尝试reduce

let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
const coords = ['x','y','z'].reduce((a,c) => Object.assign(a,{[c]: source[c]}), {});
console.log(coords);

相关内容

最新更新