Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object with a subset of properties of another object

Tags:

javascript

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.

like image 661
kamilkp Avatar asked Dec 24 '16 21:12

kamilkp


2 Answers

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);
like image 108
Nina Scholz Avatar answered Sep 18 '22 13:09

Nina Scholz


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.

like image 39
Ori Drori Avatar answered Sep 19 '22 13:09

Ori Drori