Search code examples
arraystypescriptapinestedazure-devops-extensions

Typescript array - need to remove all nested arrays that do not have defaultBranch: object


I am using the Azure DevOps Extension api to create an array of all of my repositories in ADO. This results in an array with several nested arrays.

Some of these nested arrays do not have a defaultBranch object because the repositories are empty. I would like to remove any nested arrays that are missing the defaultBranch object.

Example of current array:

repos = [{id: 123, defaultBranch: 'master', name: repo1},
         {id: 234, name: repo2},
         {id: 345, defaultBranch: 'master', name: repo3}]

I would like to remove that middle array and any others that are missing the defaultBranch, leaving me with the below array:

repos = [{id: 123, defaultBranch: 'master', name: repo1},
         {id: 345, defaultBranch: 'master', name: repo3}]

I am not sure if it would be easier to remove any nested arrays that do not meet the requirements or to create a new array that leaves them out. I am newer to Typescript/coding so I am not sure where to begin.

I appreciate any help!


Solution

  • array's filter should sort you out

    let filteredRepos = repos.filter(r => Boolean(r.defaultBranch))
    

    When the defaultBranch is non-existant, it is a "falsy" value, which means it will be discarded from the newly created array.