Ryan Taylor
Ryan Taylor

Reputation: 8892

Filter original array based on a property value of an object in an array on the original parent object

I have an array of PowerShell objects called $releases. A release contains an ID, Name, and an optional array of objects for projects associated with the release. Each project has an ID and Name property. An example is shown below.

id                  : 1
name                : Release 5
associated_projects : {@{id=50; name=Project 1}}

id                  : 2
name                : Release 6
associated_projects : {@{id=51; name=Project 2}}

id                  : 3
name                : Release 7

I want to filter the result so that only those releases that have associated projects with a specific associated project id are returned. For instance, if my associated project id were 50 I would return release 1 from the example above.

My initial approach would be to simply iterate through the releases with a nested for-each to look for the associated project's id. When found, add the releases to another array and return the result. However, it seems there may be a more appropriate way to handle this in PowerShell using Where-Object. Yet, my attempt at filter this collection based on a property value of an object in an array on the original parent object has failed.

Is there a better way to filter this that would be more idiomatic to PowerShell?

Upvotes: 6

Views: 14813

Answers (2)

ElectronicDrug
ElectronicDrug

Reputation: 48

$releases | Where-Object { $_.associated_projects.id -eq 50 }

Upvotes: 2

Rakhesh Sasidharan
Rakhesh Sasidharan

Reputation: 1063

Something like this?

PS> $releases | ?{ $_.associated_projects -ne $null }

Name                           Value
----                           -----
associated_projects            {id, name}
name                           Release 5
id                             1
associated_projects            {id, name}
name                           Release 6
id                             2

This filters out the objects whose associated_projects key is not $null.

Upvotes: 11

Related Questions