3

Consider the following object:

const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}

Is there a simple syntax for creating a new object that contains:

const obj2 = {a, b, d}

I'm aware that underscore & lodash have .pick(), but I'm hoping there's some kind of destructuring trickery that I may not be aware of.

maxedison
  • 16,472
  • 13
  • 57
  • 104
  • I can't think of anything in ES6 that's more readable than doing it the old way—`const obj2 = { a: obj.a, b: obj.b, d: obj.d };`—though repeating `obj` so many times is not that nice. – David Sherret Jun 20 '16 at 18:39

3 Answers3

8

Concise one-liner in ES2015 is

const obj2 = (({a, b, d}) => ({a, b, d}))(obj);

It doesn't seem to be possible to avoid {a, b, d} tautology while keeping it compact at the same time.

Estus Flask
  • 150,909
  • 47
  • 291
  • 441
  • Wow, I was all excited about using this ES2015 construct for the first time, but it's still not quite as elegant as I hoped. Oh well, maybe a future version. Thanks! – Michael Scheper Oct 16 '17 at 19:20
  • 1
    @MichaelScheper That's why Lodash `_.pick` is still applicable. The answers in dupe question cover it all. – Estus Flask Oct 16 '17 at 19:39
5

You can do it in two steps:

const obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
var {a, b, d} = obj;
const obj2 = {a, b, d};

If you don't want to pollute the scope,

const obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
const obj2 = {};
{
  let {a, b, d} = obj;
  Object.assign(obj2, {a, b, d});
}
Oriol
  • 225,583
  • 46
  • 371
  • 457
4

You could use Rest parameters and create custom pick function like this

const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}

function pick(object, ...p) {
  return p.reduce((o, e) => {return o[e] = object[e], o}, {});
}

console.log(pick(obj, 'a', 'b', 'd'))
Nenad Vracar
  • 102,378
  • 14
  • 116
  • 136