DEV Community

Heru Hartanto
Heru Hartanto

Posted on

7 1

How to clone object except for one or some keys

Let say you have an object that you want to use it as payload to make a request

const payload = {
    'username': 'Mark',
    'Hash' :'8fafasdf8afadsf',
    'redirectUrl':'/'
}
Enter fullscreen mode Exit fullscreen mode

but you want to exclude redirectUrl from your object before make request, and you don't want to delete this key, hmmm it is easy doesn't it, just destructuring the object and rearrange it to a new variable

    const {username,Hash} = payload;
    const newPayload = {username,Hash}
Enter fullscreen mode Exit fullscreen mode

but wait, what if your object is actually updated and now look like this

const payload = {
    'username': 'Mark',
    'Hash' :'8fafasdf8afadsf',
    'redirectUrl':'/',
    'firstname':'mark',
    'lastname':'brown',
    'birthdate':'01/12/2000',
    'gender':'MALE',
    'address':'planet earth'
}
Enter fullscreen mode Exit fullscreen mode

seems like destructuring and rearrange is kind of hardwork to do.

"Put rest to the last" technique to the rescue

simply put keys that you don't want to use and put the rest of it in the last

const payload = {
    'username': 'Mark',
    'Hash' :'8fafasdf8afadsf',
    'redirectUrl':'/',
    'firstname':'mark',
    'lastname':'brown',
    'birthdate':'01/12/2000',
    'gender':'MALE',
    'address':'planet earth'
}
let{redirectUrl, ...newPayload} = payload
newPayload
/*
    {
        'username': 'Mark',
        'Hash' :'8fafasdf8afadsf',
        'firstname':'mark',
        'lastname':'brown',
        'birthdate':'01/12/2000',
        'gender':'MALE',
        'address':'planet earth'
    }
*/

Enter fullscreen mode Exit fullscreen mode

If you want to add another key to exclude just simply put keys name after redirectUrl

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay