Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to destructure an object into a new object in es6?

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!

like image 310
reectrix Avatar asked May 17 '18 00:05

reectrix


2 Answers

You could use delete:

const newPayload = { ...payload };

delete newPayload.cat

Or:

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

Lodash also has omit():

const newPayload = _.omit(payload, ['cat']);
like image 184
Anthony Avatar answered Oct 20 '22 16:10

Anthony


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'])
like image 5
Matt Aft Avatar answered Oct 20 '22 16:10

Matt Aft