Search code examples
javascriptdestructuring

Destructure multiple keys to the same variable name


I get a response from multiple APIs with relatively the same object structure but key names might vary as example:

response1 = {name:"Something", image:"path_to_image", ...}
response2 = {title:"Something", image:"path_to_image", ...}
response3 = {label:"Something", image:"path_to_image", ...}

I want to destructure those objects to the same variable name:

const {name|title|label: title, ...rest} = response

in order to use it in the component without the need for multiple checks for object keys like this as example:

const title = response?.title || response?.name || response?.label;

Can it be done with destructure directly or any one line solution?


Solution

  • You could do something weird with default initialisers:

    const {name, label=name, title=label, ...rest} = response;
    // or
    const {name, label, title = name ?? label, ...rest} = response;
    

    Notice however that this will also declare the variables name and label. Your one-line solution is much cleaner and better to understand:

    const title = response.title ?? response.name ?? response.label;
    

    Alternatively, if you really have a lot of properties, you might want to loop:

    const key = ['name', 'title', 'label', 'subject', 'content', 'body'].find(key => key in response);
    const {[key]: title, ...rest} = response;