-1

我有两个需要使用 Angular cli 6.0 嵌套的 json

我是角度新手,所以我需要帮助..

json 1

[{"Name": "Fields1",
"DFields":["Fields1_1","Fields1_2"]
},
{"Name": "Fields2",
"DFields":["Fields2_1"]
}]

json 2

[
{"Id": "1", "Fields1_1": 1 , "Fields1_2": 1, "Fields2_1: 1},
{"Id": "2", "Fields1_1": 1 , "Fields1_2": 0, "Fields2_1: 1} 
{"Id": "3", "Fields1_1": 1 , "Fields1_2": 1, "Fields2_1: null} 
]

循环遍历字段并计算其相应数据的更快方法是什么..哪个计数不应该为空或零..

样本应该返回一个数组..

Fields1_1 = 3
Fields1_2 = 2
Fields2_1 = 2

请注意,这些字段是动态的,可以根据 json 进行更改

4

1 回答 1

0

RxJs v6 解决方案 :)

    const json1 = [
  { "Name": "Fields1", "DFields": ["Fields1_1", "Fields1_2"] },
  { "Name": "Fields2", "DFields": ["Fields2_1"] }
];

const json2 = [
  { "Id": "1", "Fields1_1": 1, "Fields1_2": 1, "Fields2_1": 1 },
  { "Id": "2", "Fields1_1": 1, "Fields1_2": 0, "Fields2_1": 1 },
  { "Id": "3", "Fields1_1": 1, "Fields1_2": 5, "Fields2_1": null }
];

from(json2).pipe(
  map(obj => Object.keys(obj).map(k => { return { key: k, val: obj[k] } })),
  flatMap(kvPairArray => from(kvPairArray)),
  groupBy(kvPair => kvPair.key),
  filter(group => json1.map(a => a.DFields).reduce((acc, curr) => [...acc, ...curr], []).includes(group.key)),
  mergeMap(group => group.pipe(
    filter(groupEntry => groupEntry.val !== null && groupEntry.val !== 0),
    reduce<{key: string, val: number},number>((acc, groupEntry) => acc + groupEntry.val, 0),
    map(count => {
      return {
        key: group.key,
        count: count
      };
    })
  )),
  toArray()
).subscribe(result => console.log(result));
于 2018-06-04T20:14:39.467 回答