我的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"]}]
}]
此结果是compareResults变量。现在,我试图根据每个记录的工件数据(hasVersionDiff标志为true)对此进行过滤。我正在尝试使用以下过滤器:
this.compareResults.map(function(ComparisonResult) {
ComparisonResult.artifacts = ComparisonResult.artifacts.filter(x => x.hasVersionDiff == true)
});
但是它没有过滤,有人可以解释为什么它不起作用吗?
答案 0 :(得分:1)
由于map
,您需要return
新项目。 (我还修复了您的对象结构,使其有效):
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; }
如果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; }
答案 1 :(得分:0)
我实现了递归函数,通过它可以从上到下逐层过滤嵌套的对象数组。在 TS playground
中探索、播放和修改我的脚本