javascript 如何在脚本中属性化创建和引用动态变量名

jm2pwxwz  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(127)

我有一段代码是手动运行的,但是我正在努力提高可重用性。在函数的当前状态下,它设置了一个手动创建的数组的大列表。然后为每周快照数执行一个DB调用,并通过一个带有开关/case的foreach排序将这些值推入正确的数组中。在此过程中,它还将所有记录的工作周列表放在一起。然后删除重复项,将这些工作周转换为字符串,并将它们推送到自己的数组中。然后,它运行实时数据查询,并将结果推送到现有数组中。之后,它返回构建的对象。
代码如下所示:

globalCap: async function (req, res) {
        try {
            let af = [], workweeks = [], bf = [], ca = [], da = [], fr = [], gl = [], ch = [];
            let snapshots = await Snapshot.find().sort('createdTS ASC');
            snapshots.forEach(element => {
                switch (element.parentLocation) {
                    case 'AF':
                        af.push(element.totalSpaces);
                        break;
                    case 'BF':
                        bf.push(element.totalSpaces);
                        break;
                    case 'CA':
                        ca.push(element.totalSpaces);
                        break;
                    case 'DA':
                        da.push(element.totalSpaces);
                        break;
                    case 'FR':
                        fr.push(element.totalSpaces);
                        break;
                    case 'CH':
                        ch.push(element.totalSpaces);
                        break;
                    default:
                        break;
                }
                workweeks.push(element.workweek);
            });

            let uniqueWW = [...new Set(workweeks)];
            uniqueWW.forEach(element => {
                i = 'WW' + element;
                gl.push(i);
            });

            let afLive = await Location.count({
                parentLocationID: 1
            });
            af.push(afLive);
            let bfLive = await Location.count({
                parentLocationID: 2
            });
            bf.push(bfLive);
            let caLive = await Location.count({
                parentLocationID: 3
            });
            ca.push(caLive);
            let daLive = await Location.count({
                parentLocationID: 4
            });
            da.push(daLive);
            let frLive = await Location.count({
                parentLocationID: 5
            });
            fr.push(frLive);
            let chLive = await Location.count({
                parentLocationID: 6
            });
            ch.push(chLive);
            ww = 'WW' + workweek();
            gl.push(ww);
            return res.ok({
                'AF': af,
                'BF': bf,
                'CA': ca,
                'DA': da,
                'FR': fr,
                'CH': ch,
                'ww': gl,
            });
        }
        catch (error) {
            console.error(error);
        }
    },

并将其输出以用于前端的某些图表:

{
        "AF": [80,80,80],
        "BF": [131,131,131],
        "CA": [0,0,0],
        "DA": [78,78,78],
        "FR": [0,0,0],
        "CH": [0,171,171],
        "ww": ["WW1","WW2","WW3"]
      }

但是,随着数据量的增长,我希望根据查询结果动态创建数组。
所以我在开头添加了一个siteInfo查询,它将提取并Map到我需要的两个组件,campusCode和id:

const siteInfo = await ParentLocation.find();
    const sites = siteInfo.map(obj => ({
        campusCode: obj.campusCode,
        id: obj.id
    }));

它给出以下输出:

[
    { campusCode: 'AF', id: 1 },
    { campusCode: 'BF', id: 2 },
    { campusCode: 'CA', id: 3 },
    { campusCode: 'DA', id: 4 },
    { campusCode: 'FR', id: 5 },
    { campusCode: 'CH', id: 6 }
  ]

排序快照数据并将其推送到数组中,然后再次引用它们以基于parentLocationID查询将“实时”数据推送到每个数组的末尾,最好的方法是什么?我觉得有一种更简单的方法可以做到这一点,但我对它的研究越来越深入。

oug3syen

oug3syen1#

代替所有这些变量,用所有键初始化一个对象,然后你可以在snapshots.forEach()循环中动态地给键赋值,并在调用Location.count()时再次循环它们。
ww键将单独添加到循环后,因为它与其余键不同。

globalCap: async function(req, res) {
  try {
    let af = [],
      workweeks = [],
      result = {
        'AF': [],
        'BF': [],
        'CA': [],
        'DA': [],
        'FR': [],
        'CH': [],
      };
    let snapshots = await Snapshot.find().sort('createdTS ASC');
    snapshots.forEach(element => {
      if (element.parentLocation in result) {
        result[element.parentLocation].push(element.totalSpaces);
        workweeks.push(element.workweek);
      }
    });

    let uniqueWW = [...new Set(workweeks)];
    let gl = uniqueWW.map(element => 'WW' + element);
    gl.push('WW' + workweek());

    let index = 0;
    for (let k in result) {
      let live = await Location.count({
        parentLocationID: ++index
      });
      result[k] = live;
    }

    result.ww = gl;
    return res.ok(result);
  } catch (error) {
    console.error(error);
  }
},
7cwmlq89

7cwmlq892#

我在这里得到的答案很有帮助,谢谢!在重构了一些东西之后,我现在能够可靠地构建对象,而不管初始查询返回多少结果。下面是我最终使用的代码:

globalCap2: async function (req, res) {
        try {
            let gl = [], workweeks = [], campusSpaces = {};
            const siteInfo = await ParentLocation.find();
            const sites = siteInfo.map(obj => ({
                campusCode: obj.campusCode,
                id: obj.id
            }));

            sites.forEach(element => {
                const campusCode = element.campusCode;
                campusSpaces[campusCode] = {};
                campusSpaces[campusCode].id = element.id;
                campusSpaces[campusCode].trend = [];
            });

            let snapshots = await Snapshot.find().sort('createdTS ASC');
            snapshots.forEach(element => {
                const campusCode = element.parentLocation;
                if (campusSpaces[campusCode]) {
                    campusSpaces[campusCode].trend.push(element.totalSpaces);
                }
                workweeks.push(element.workweek);
            });

            for (let key in campusSpaces) {
                id = campusSpaces[key].id
                let live = await Location.count({
                    parentLocationID: id
                });
                campusSpaces[key].trend.push(live);
            }

            let uniqueWW = [...new Set(workweeks)];
            uniqueWW.forEach(element => {
                i = 'WW' + element;
                gl.push(i);
            });
            ww = 'WW' + workweek();
            gl.push(ww);
            campusSpaces.WW = gl;

            return res.ok(campusSpaces);
        }
        catch (error) {
            console.error(error);
        }
    },

相关问题