计算从另一个Json数组

时间:2018-06-04 19:21:04

标签: angular angular-cli-v6

我有两个json,我需要使用Angular cli 6.0

进行嵌套

我是棱角分明的新人,所以我需要帮助..

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} 
]

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

示例应该返回一个数组..

Fields1_1 = 3
Fields1_2 = 2
Fields2_1 = 2

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

1 个答案:

答案 0 :(得分: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));