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
  • 17,243
  • 14
  • 67
  • 114
  • 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
  • 206,104
  • 70
  • 425
  • 565
  • 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
  • 274,082
  • 63
  • 437
  • 513
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
  • 118,580
  • 15
  • 151
  • 176