Get an object with a subset of the properties of another object

I know this existing question , however, I'm only interested in simple javascript solutions (without external libraries like lodash).

What would be the cleanest way (including all the goodnesses of ES6 and beyond - like rest and distribution of objects, etc.) to get an object with a subset of details from another object in javascript?

Say I want to select foo , bar and baz from a source object. I currently have two solutions, I don't like any of them:

1.

 const result = { foo: source.foo, bar: source.bar, baz: source.baz }; 

2.

 const { foo, bar, baz } = source; const target = { foo, bar, baz }; 

The second option is shorter, but it pollutes the current execution area with some variables, and their list should be written twice in any case.

PS. I'm also not interested in incrementing Object.prototype with some helper method or calling some user-defined functions to achieve this.

+5
source share
3 answers

You can use IIFE with destruction.

 const source = { foo: 1, bar: 2, baz: 3 }, target = (({ foo, bar, baz }) => ({ foo, bar, baz }))(source); console.log(target); 
+2
source

If you have an object that contains many properties that you need, and in a small amount, you cannot use the object stop syntax :

 const source = { foo: 1, bar: 2, baz: 3, whatever: 4 }; const { whatever, ...target } = source; console.log(target); 

Note The remainder of the object is the 3rd stage proposal for ECMAScript and the transpiler (babel with Object Spread Conversion ).

+1
source

You can use destructuring assignment

 const source = {foo: 1, bar:2, baz:3, abc: 4, def: 5}; const result = {}; ({foo:result.foo, bar:result.bar, baz:result.baz} = source); console.log(result); 

Alternatively, you can specify property names as elements of an array, use a for..of with the purpose of destructuring to set properties, target values

 const source = {foo: 1, bar:2, baz:3, abc:4, def: 5}; const result = {}; for (let prop of ["foo", "bar", "baz"]) ({[prop]:result[prop]} = source); console.log(result); 
0
source

Source: https://habr.com/ru/post/1261852/


All Articles