11

For instance, I have this object:

const payload = {
    apple: 1,
    dog: 2,
    cat: 3
}

and I want to destructure it into a new object that only contains apple and dog:

const newPayload = {
    apple:1,
    dog: 2
}

Something like:

const {{apple, dog} : newPayload} = payload

Obviously the above is wrong, but wondering if there is a way to do something like this.

Thanks!

reectrix
  • 7,999
  • 20
  • 53
  • 81
  • this isn't "destructuring" (that would be converting from a tuple to individual named variables), but a shallow-copy with a property filter. – Dai May 17 '18 at 00:14
  • 2
    this way is ugly ... `const newPayload = (({apple, dog}) => ({apple, dog}))(payload)` – Jaromanda X May 17 '18 at 00:18
  • 1
    Possible duplicate of [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – Dai May 17 '18 at 00:18
  • @Dai No, this is not duplicate of that question. This is different – Zohaib Ijaz May 17 '18 at 00:23
  • the benefit of my ugly code is ... no spurious const's littering the code :p – Jaromanda X May 17 '18 at 00:24
  • @ZohaibIjaz how is it not a duplicate? This Q's OP wants to clone an object using only a subset of that object's properties, that's exactly what's going on in the linked QA. – Dai May 17 '18 at 00:24
  • OP is looking for destructing based solution, which is not there in your specified link. – Zohaib Ijaz May 17 '18 at 00:26
  • 2
    a less ugly non polluting way is `const newPayload = (({ cat, ...x }) => x)(payload);` – Jaromanda X May 17 '18 at 00:36
  • @JaromandaX What is this technique or concept called `const newPayload = (({apple, dog}) => ({apple, dog}))(payload)`? I want to read about it and how it works. Thanks – newbie Nov 26 '22 at 00:16
  • 1
    It's an IIFE @newbie – Jaromanda X Nov 26 '22 at 04:16

2 Answers2

11

You could use delete:

const newPayload = { ...payload };

delete newPayload.cat

Or:

const { cat, ...newPayload } = payload;

Lodash also has omit():

const newPayload = _.omit(payload, ['cat']);
Anthony
  • 6,422
  • 2
  • 17
  • 34
5

Probably in two steps:

const payload = {
    apple: 1,
    dog: 2,
    cat: 3
}

const { apple, dog } = payload

const newPayload = {
    apple,
    dog,
}

Or you can use lodash _.pick :

const newPayload = _.pick(payload, ['apple', 'dog'])
Matt Aft
  • 8,742
  • 3
  • 24
  • 37