Search code examples
javascriptecmascript-6javascript-objects

How to destructure and reassign in one line using JavaScript


I have an object adData and I need to extract some of it's properties, add some more properties to the extracted object and pass the object as parameter. I can do this using:

const params = {}; 
params.id = adData.id;  
params.status = adData.status; 
params.frequency = adData.frequency; 
params.user = getLoggedInUser(); 
callAnotherFunction(params)

Can I do the destructing and reassigning to new object in one line ? Something like:

const params = {id, status, frequency} = adData; 
params.user = getLoggedInUser(); 

Or

const params = {id, status, frequency, getLoggedInUser(): user} = adData; 

Now these both above syntaxes are wrong but is there any other way to do it using destructuring and without extracting the properties one by one


Solution

  • If you know what properties the object does have, and there aren't that many, you can list them and use rest syntax to gather the others into an object:

    const { unwantedProp, ...params) = adData;
    // use params
    

    Otherwise, there isn't any incredibly simple syntax for what you want, though you could

    const params = Object.fromEntries(
      Object.entries(adData).filter(([key]) => 
        ['id', 'status', 'frequency'].includes(key)
      )
    );