【问题标题】:Javascript reduce in other functionJavascript减少其他功能
【发布时间】:2020-10-05 20:06:47
【问题描述】:

如何从我的 JSON 文件中获取我解析的数据以运行 reduce 函数以消除重复项,然后通过调用 getFiilteredData() 函数获得可用的数据?

async function getFilteredData() {
        return new Promise((resolve) => {
          oWebViewInterface.on("loadData", function (data) {
            var schwellWerte = data.monitor;
            var monitorData = data.data.reduce((arr, d) => {
              if (arr.find((i) => i.zeitstempel === d.zeitstempel)) {
                return arr;
              } else {
                return [...arr, d];
              }
            }, []);
            resolve(monitorData); // resolve the promise with the data
            //can I do: resolve(monitorData, schwellWerte) to resolve both?
          });
        });
      }

这样做会导致最后两个 console.log() 出现“Uncaught TypeError: Cannot read property '0' of undefined”,但第一个工作正常并记录预期值。

【问题讨论】:

  • 顺便说一句,为什么不使用filter 而不是reduce
  • 什么是oWebViewInterface
  • 它只是一个 nsWebViewInterface,因为这是来自 NativeScript 移动应用程序的代码

标签: javascript json reduce


【解决方案1】:

最简单的方法是使用 Promise 和 async/await。将您的异步调用包装在 Promise 中并在客户端等待它:

async function getFilteredData() {
    return new Promise( resolve => {
        oWebViewInterface.on("loadData", function (data) {
          var monitorData = JSON.parse(data).reduce((arr, d) => {
            if (arr.find((i) => i.zeitstempel === d.zeitstempel)) {
              return arr;
            } else {
              return [...arr, d];
            }
          }, []);
          resolve(monitorData); // resolve the promise with the data
        });
    });
}

然后当您调用它时,只需 await 调用

var filteredData = await getFilteredData();
console.log(filteredData[0].id);

编辑:我从您的 cmets 中注意到,您在代码中调用了两次 getFilteredData - 这似乎是个坏主意。调用一次。如果您将图表的配置放入其自己的async 方法中,这将变得更容易

async function configChart(){
      var data = await getFilteredData();
      var werteArr = [];
      var zsArr = [];
      for (i = 0; i < data.length; i++) {
         werteArr.push(data[i].wert);
         zsArr.push(data[i].zeitstempel);
      }
        

      //defining config for chart.js
      var config = {
        type: "line",
        data: {
          labels: zsArr ,
          datasets: {
            data: werteArr,
            // backgroundcolor: rgba(182,192,15,1),
          },
        },
        // -- snip rest of config -- //
     }
     var ctx = document.getElementById("canvas").getContext("2d");
     window.line_chart = new window.Chart(ctx, config);
}

window.onload = function () {
    configChart(); // no need to await this. It'll happen asynchronously
};

【讨论】:

  • 我尝试了您的解决方案,但我无法进行顶级等待...“未捕获的语法错误:等待仅在异步函数中有效”
  • @CRoNiC 你只需要制作顶级函数async
  • 我试过了,但是由于我还是遇到了一些我无法解决的问题,也许你有时间看一下完整代码:codepile.net/pile/Z5wZpQ3O
  • 您的代码有效,但我再次需要您的帮助,因为我意识到我并不完全理解您的代码...我需要返回比以前更多的数据 - 请参阅更新的代码。
  • 写完评论以为自己能解决,但没能解决
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 2018-10-29
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
相关资源
最近更新 更多