2

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

shrekDeep
  • 2,260
  • 7
  • 27
  • 39

2 Answers2

1

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)
  )
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

We can do in one line with destructuring and arrow function.

const getLoggedInUser = () => "foo";
const adData = {
  id: 123,
  status: "active",
  frequency: "less",
  bar: 4,
};

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

console.log({ params });
Siva K V
  • 10,561
  • 2
  • 16
  • 29