6

I am aware of this existing question however I am interested in only plain javascript solutions (with no external libs like lodash).

What would be the cleanest way (including all ES6 goodness and beyond - like object rest & spread etc.) to get an object with a subset of props from another object in javascript?

Lets say I want to pick foo, bar, and baz from source object. I currently have two solutions, I like neither 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 one is shorter but it pollutes current execution scope with some variables and the list of them has to be written twice anyway.

PS. I am also not interested in augmenting Object.prototype with some helper method or calling some custom function to achieve this.

Community
  • 1
  • 1
kamilkp
  • 9,690
  • 6
  • 37
  • 56

3 Answers3

2

You could use an IIFE with a destruction.

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

console.log(target);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

If you've got an object that contains many properties you need, and and a small amount you don't, you can use the object rest syntax:

const source = { foo: 1, bar: 2, baz: 3, whatever: 4 };

const { whatever, ...target } = source;

console.log(target);

Note - Object rest is a a Stage 3 proposal for ECMAScript, and a transpiler (babel with the Object rest spread transform) is needed.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

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 set property names as elements of an array, use for..of loop with destructuring assignment to set properties, values of target

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);
guest271314
  • 1
  • 15
  • 104
  • 177