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.

1
  • 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. Commented Jun 20, 2016 at 18:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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!
@MichaelScheper That's why Lodash _.pick is still applicable. The answers in dupe question cover it all.
it doesn't seem shorter than const obj = {a: obj.a, b: obj.b, d: obj.d}. It depends if you want to keep the obj reference or clone the values
@venimus You likely meant "const obj2". It doesn't work differently, both make a shallow copy of obj. Whether it's shorter depends on the size of "obj" name, but a, b, d is quicker to write because it can be copied and pasted
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});
}

Comments

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'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.