如何在TypeScript中过滤ADO仓库数组中无defaultBranch的项?
过滤Azure DevOps仓库数组,移除缺少defaultBranch属性的对象
问题描述
通过Azure DevOps Extension API获取到仓库数组后,部分仓库对象缺少defaultBranch属性,需要移除这些不符合要求的对象。
原数组示例:
const repos = [ {id: 123, defaultBranch: 'master', name: 'repo1'}, {id: 234, name: 'repo2'}, {id: 345, defaultBranch: 'master', name: 'repo3'} ];
期望得到的数组:
const filteredRepos = [ {id: 123, defaultBranch: 'master', name: 'repo1'}, {id: 345, defaultBranch: 'master', name: 'repo3'} ];
解决方案
在TypeScript中,创建新数组是最简洁、安全的方式,不需要修改原数组,直接用数组的filter()方法即可实现需求:
基础过滤(仅检查属性存在)
如果只需要移除完全缺少defaultBranch属性的对象,使用以下代码:
const filteredRepos = repos.filter(repo => 'defaultBranch' in repo);
增强过滤(确保属性有有效值)
如果有些仓库虽然存在defaultBranch但值为null或undefined,需要一并过滤,可以调整判断条件:
const filteredRepos = repos.filter(repo => repo.defaultBranch != null);
代码说明
filter()是数组内置方法,会遍历原数组并返回新数组,仅保留满足判断条件的元素'defaultBranch' in repo用于严格检查对象是否包含目标属性,适配“属性完全缺失”的场景repo.defaultBranch != null会同时排除属性值为null或undefined的情况,覆盖更多无效场景
为什么不修改原数组?
直接修改原数组(比如用splice删除元素)需要倒序遍历数组,代码逻辑更繁琐;而且API返回的数组通常不建议直接修改,创建新数组更符合函数式编程的规范,也能避免意外修改原数据引发的问题。
内容的提问来源于stack exchange,提问作者Keebler
相关产品推荐
相关产品推荐

