DEV Community

loading...

How to clone object except for one or some keys

elukuro profile image Heru Hartanto ・1 min read

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

Discussion (0)

Forem Open with the Forem app