Elegant way to copy only a part of an object [duplicate]

One way to do it is through object destructuring and an arrow function:

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

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

console.log(result);

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.

Leave a Comment