0

So, what i have:

const obj = { a: 1, b: 2, c: 3 };
const { a, c } = obj;
const newObj = { a, c };
//newObj is { a: 1, c: 3 } now

What i kinda want to have:

const newObj = { a, c } = obj
//newObj is { a: 1, c: 3 } now

Looks much cleaner for big objects (but dont work, obviously). Any ideas?

Summary: lodash.pick mentioned by @wostex is best solution for now

Dmitrii S.
  • 28
  • 3
  • 2
    lodash.pick maybe? – Egor Stambakio Jan 31 '18 at 19:32
  • I don't think there is a way to do anything similar since the return value of `let a,c;{a, c} = obj` is `obj` and not an anonymous temporary object `{ a, c }` – Patrick Roberts Jan 31 '18 at 19:34
  • @wostex nice one, but it would be more elegant with raw js if possible – Dmitrii S. Jan 31 '18 at 19:35
  • 1
    Upcoming ES2018 has [rest properties destructuring](http://2ality.com/2016/10/rest-spread-properties.html). It's the other way around tho, object from props not mentioned instead of object from props mentioned. Until then, lodash. – Joseph Jan 31 '18 at 19:36

1 Answers1

1

There's no particularly clean way to do this. I do it with an inline function by leveraging parameter destructuring:

const newObj = (({a,b,c})=>({a,b,c}))(originalObj)

The downside to this solution is that it is not dynamic. You can not, for example, create a pluck function that retrieves a dynamic list of properties using this.

Brennan
  • 5,160
  • 2
  • 14
  • 23
  • Chrome console: var originalObj = {a: 1, b: 2, c: 3}; const newObj = (({a,b,c})=>(a,b,c))(originalObj); console.log(newObj); // output is '3' No idea how that happened – Dmitrii S. Jan 31 '18 at 19:40
  • 1
    @DmitriiS. I had a typo that I have fixed – Brennan Jan 31 '18 at 19:41