简体   繁体   中英

Is it possible to destruct a large object only once in Javascript's function?

I am using a function to destruct a set of data, then this data is basically treated before returning it.

here it is a POC/sample to illustrate about it:

function getDocsData(startWeek) {
    // first time to destruct the data
    let {
        mon,
        tue,
        wed,
    } = startWeek;

    mon = mon ? mon.total : 0;
    tue = tue ? tue.total : 0;
    wed = wed ? wed.total : 0;

    // second time repeats the data so that I can have my treated data returned
    return {
       mon,
       tue,
       wed,
   }
}

This is fine if you have a few variables to be treated, but in my case I have to treat more than 30 objects.

Note: I aware that I can use this instead:

return {
    mon: startWeek.mon ? startWeek.mon.total : 0;
    ...
}

These solutions are the best it can gets or there is a better way to avoid repeat the object { mon, tue, wed } or write startWeek. everywhere?

I'd map an array of the object properties to a new object with Object.fromEntries , no need to list the days at all:

const getDocsData = startWeek => Object.fromEntries(
  Object.entries(startWeek)
    .map(([key, val]) => [key, value ? value.total : 0])
);

If the startWeek could have other undesirable properties, iterate over an array of the desirable properties:

const props = ['mon', 'tue', 'wed'];
const getDocsData = startWeek => Object.fromEntries(
  props.map(key =>
    [startWeek[key] ? startWeek[key].total : 0]
  )
);

A less drastic tweak, which could be a slightly improvement on your original code, would be to return the new values inline in the returned object, no need to reassign:

function getDocsData(startWeek) {
    const {
        mon,
        tue,
        wed,
    } = startWeek;
    return {
       mon: mon ? mon.total : 0,
       tue: tue ? tue.total : 0,
       wed: tue ? wed.total : 0,
   }
}

If the values, if falsey, will be null or undefined, you can also use optional chaining instead of the conditional operator:

return {
   mon: mon?.total ?? 0,
   tue: tue?.total ?? 0,
   wed: wed?.total ?? 0,
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM