循环遍历JSON-需要逻辑来计算值的总和

时间:2019-04-04 02:58:14

标签: python json algorithm typescript logic

我正在尝试从下面的JSON获取键ng serve的值之和。

总和= 193(21 + 52 + 52 + 68)

我将在这里使用循环,而不是直接访问-response ['jobs'] ['0'] ['lastBuild'] ['number']。 任何人都可以提供逻辑吗?任何编程语言都可以。

npm v 6.4.1 
Angular CLI: 7.3.5  
Node: 10.15.3  
OS: linux x64  
Angular: 6.1.10  
... animations, common, compiler, core, forms, http
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router    

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.8.4
@angular-devkit/build-angular      0.13.4
@angular-devkit/build-ng-packagr   0.8.4
@angular-devkit/build-optimizer    0.13.4
@angular-devkit/build-webpack      0.13.4
@angular-devkit/core               0.8.4
@angular-devkit/schematics         7.3.5
@angular/cdk                       6.4.7
@angular/cli                       7.3.5
@angular/compiler-cli              7.2.12
@angular/fire                      5.1.0
@angular/flex-layout               7.0.0-beta.24
@angular/material                  6.4.7
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.3.4
@schematics/angular                7.3.5
@schematics/update                 0.13.5
ng-packagr                         4.7.1
rxjs                               6.2.1
typescript                         3.1.6
webpack                            4.29.0

}

2 个答案:

答案 0 :(得分:1)

递归使用Array.prototype.reduce

type Job = {lastBuild: {number: number}, jobs?: Job[]}

const reduction = (acc: number, job:Job) => acc + job.lastBuild.number 
      + (job.jobs ? job.jobs.reduce(reduction,0) : 0); // recursion

response.jobs.reduce(reduction, 0);

答案 1 :(得分:1)

python:

def sum_(s, dict_):
    return s + reduce(sum_, dict_.get("jobs", []), 0) + dict_.get("lastBuild", {}).get("number", 0)


reduce(sum_, response["jobs"], 0)