Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a subset object, consisting of only some of the properties of an existing object [duplicate]

This is best explained by example. The following works in es6 to create an object consisting of some of the keys of an existing object:

var o = {a:1, b: 2, c: 3}
var {a, c} = o
var subsetObj = {a, c} // will be: {a:1, c:3}

There are two downsides here:

  1. It took two statments, and two lines, to create the desired subset object
  2. We had to pollute the local variable scope by creating the intermediary a and c variables, which aren't needed locally, except as a means to creating our subset object.

Is there a way to accomplish the same thing in a single statement, without introducing the unnecessary locals a and c?

like image 860
Jonah Avatar asked Jun 22 '15 19:06

Jonah


1 Answers

There is no specific syntax for this. You can keep doing:

var subsetObj = {a: o.a, c: o.c};

If you have more properties or a variable number of properties, create a helper function.

Related: Is it possible to destructure onto an existing object? (Javascript ES6)

like image 153
Felix Kling Avatar answered Nov 14 '22 14:11

Felix Kling