简体   繁体   English

是否可以在 Javascript 的 function 中只破坏一次大型 object?

[英]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.我正在使用一个function来破坏一组数据,那么这个数据基本上是在返回之前处理的。

here it is a POC/sample to illustrate about it:这是一个 POC/示例来说明它:

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.如果您要处理一些变量,这很好,但在我的情况下,我必须处理 30 多个对象。

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.这些解决方案是最好的,或者有更好的方法来避免重复 object { mon, tue, wed }或写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:我将 map 一个 object 属性的数组添加到一个新的 object 与Object.fromEntries不需要列表的第 3 天。

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:如果startWeek可能有其他不需要的属性,请遍历一组需要的属性:

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:一个不太剧烈的调整(可能是对原始代码的轻微改进)是在返回的 object 中内联返回新值,无需重新分配:

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:如果值(如果为假)将为 null 或未定义,您还可以使用可选链接而不是条件运算符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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