简体   繁体   English

基于 Typescript 中嵌套对象数组的值进行过滤

[英]Filter based on value of nested array of objects in Typescript

My json data is of below structure:我的 json 数据具有以下结构:

[
{"domain":"d1",
"technology":"Java",
"artifacts[{ 
  "artifactName":"app1",
  "hasVersionDiff":true,
  "environment":["DEV","SQA"],
  "version":["Not Available","1.0-R1"]
}]},

{"domain":"d2",
"technology":".net",
"artifacts[{ 
  "artifactName":"app4",
  "hasVersionDiff":false,
  "environment":["DEV","SQA"],
  "version":["1.0-R1","1.0-R1"]}]
}]

This result is compareResults variable.这个结果是 compareResults 变量。 Now I am trying to filter this based on artifacts data (hasVersionDiff flag true) of each record.现在我试图根据每个记录的工件数据(hasVersionDiff 标志为真)过滤它。 I am trying to filter using below:我正在尝试使用以下方法进行过滤:

this.compareResults.map(function(ComparisonResult) {
        ComparisonResult.artifacts = ComparisonResult.artifacts.filter(x => x.hasVersionDiff == true)
    });

But it is not filtering, can someone explain why this is not working?但这不是过滤,有人可以解释为什么这不起作用吗?

Because with map , you need to return the new item.因为使用map ,您需要return新项目。 (I also fixed your object structure to make it valid): (我还修复了您的对象结构以使其有效):

 const compareResults = [{ "domain": "d1", "technology": "Java", "artifacts": [{ "artifactName": "app1", "hasVersionDiff": true, "environment": ["DEV", "SQA"], "version": ["Not Available", "1.0-R1"] }] }, { "domain": "d2", "technology": ".net", "artifacts": [{ "artifactName": "app4", "hasVersionDiff": false, "environment": ["DEV", "SQA"], "version": ["1.0-R1", "1.0-R1"] }] } ]; const modified = compareResults.map(function(ComparisonResult) { ComparisonResult.artifacts = ComparisonResult.artifacts.filter(x => x.hasVersionDiff); return ComparisonResult; }); console.log(modified);
 .as-console-wrapper { max-height: 100% !important; top: auto; }

If you want to remove the entire object if artifacts is empty:如果您想在artifacts为空的情况下删除整个对象:

 const compareResults = [{ "domain": "d1", "technology": "Java", "artifacts": [{ "artifactName": "app1", "hasVersionDiff": true, "environment": ["DEV", "SQA"], "version": ["Not Available", "1.0-R1"] }] }, { "domain": "d2", "technology": ".net", "artifacts": [{ "artifactName": "app4", "hasVersionDiff": false, "environment": ["DEV", "SQA"], "version": ["1.0-R1", "1.0-R1"] }] } ]; const modified = compareResults.map(function(ComparisonResult) { ComparisonResult.artifacts = ComparisonResult.artifacts.filter(x => x.hasVersionDiff); return ComparisonResult; }).filter(({ artifacts }) => artifacts.length); console.log(modified);
 .as-console-wrapper { max-height: 100% !important; top: auto; }

I implemented recursive function with which nested array of objects can be filtered layer by layer from top to bottom.我实现了递归函数,通过它可以从上到下逐层过滤嵌套的对象数组。 Explore, play and modify my script in TS playgroundTS playground 中探索、播放和修改我的脚本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM