从特定的javascript对象属性中提取值

时间:2018-10-10 10:15:13

标签: javascript

我有一些似乎可以正常工作的代码:

async function myfunction(ref) {
  var r1 = await getReport(ref, "queue", "hour", "2018-10-03", "2018-10-04", "pageviews", "page");
  var r2 = await getReport(r1.reportID, "get").then(r2 => reportHandler(r1.reportID, r2, 0));
  console.log(r2);
}

console.log(r2);输出以下结果:

{report: {…}, waitSeconds: 0, runSeconds: 0}
report:
data: Array(4)
0:
breakdown: [{…}]
breakdownTotal: ["608674"]
day: 1
month: 10
name: "Mon.  1 Oct. 2018"
year: 2018
__proto__: Object
1:
breakdown: [{…}]
breakdownTotal: ["564566"]
day: 2
month: 10
name: "Tue.  2 Oct. 2018"
year: 2018

我正在尝试使用通过在线教程构建的代码输出'breakdownTotal'的值

const result = data.report.data.reduce((r, e) => {
  e.breakdownTotal.forEach(el => {
    let key = "data";
    if(!r[key]) r[key] = []
    r[key].push(...el.counts)
  })
  return r;
}, {})

但是,出现此错误:

Uncaught (in promise) ReferenceError: data is not defined
    at myfunction (mytest3.html:12)

1 个答案:

答案 0 :(得分:2)

r2返回myFunction

async function myfunction(ref) {
  var r1 = await getReport(ref, "queue", "hour", "2018-10-    03", "2018-10-04", "pageviews", "page");
  var r2 = await getReport(r1.reportID, "get").then(r2 =>    reportHandler(r1.reportID, r2, 0));
  return r2;
}

data创建myFunction(ref);

const data= await myFunction(ref);
if(data!=null && data.report.data!=null){
const result = data.report.data.reduce((r, e) => {
  e.breakdownTotal.forEach(el => {
  let key = "data";
   if(!r[key]) r[key] = []
    r[key].push(...el.counts)
  })
  return r;
  }, {})
}