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!
You could use delete
:
const newPayload = { ...payload };
delete newPayload.cat
Or:
const { cat, ...newPayload } = payload;
Lodash also has omit()
:
const newPayload = _.omit(payload, ['cat']);
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With