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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With