2

I want to remove an array element from json array (PSObject) if value matches as follows:

$code = 12345
$myObject = @{ ArrayPair= @(@{ code = 12345; perm = "RW" }, @{ code = 23456; perm = "RW" })}

if ($true) { # $revoke
      $myObject.ArrayPair = $myObject.ArrayPair | Where-Object -FilterScript {$_.code -ne $code}
}

At the start ArrayPair has 2 array elements, after executing the filter, ArrayPair is no longer an array but rather an object with two elements. How can I keep it as an array so I can continue to add new pairs to the array?

json Values before and After removal: Before value:

 {"ArrayPair":  [{"perm":  "RW","code":  12345},{"perm":  "RW","code":  23456}]}

After Value removal

{"ArrayPair":  { "perm":  "RW", "code":  23456 }}

2 Answers2

0

You can force the object to stay an array like this:

$code = 12345
$myObject = @{ ArrayPair= @(@{ code = 12345; perm = "RW" }, @{ code = 23456; perm = "RW" })}
[array]$myObject.ArrayPair = $myObject.ArrayPair | Where-Object -FilterScript {$_.code -ne $code}

$myObject.ArrayPair.GetType()
#Returns
#IsPublic IsSerial Name                                     BaseType
#-------- -------- ----                                     --------
#True     True     Object[]                                 System.Array

To add additional entries to your array you have to try it like this:

$myObject.ArrayPair += @{code = 2134; perm= "RR"}

This way you can add entries to the array and the result looks like this:

PS C:\> $myObject.ArrayPair

Name                           Value
----                           -----
code                           23456
perm                           RW
code                           2134
perm                           RR

Please be aware that += doens't really add objects to the array, but instead recreates the array with new values. If you try to add the objects via $myObject.ArrayPair.Add(@{code = 2134; perm= "RR"}) you get an error.

Please take a look at this answer for further explanations: PowerShell Array.Add vs +=

Paxz
  • 2,959
  • 1
  • 20
  • 34
0

I while deleting elements if there was just one left, I found that I had to double force the object to make sure that it remained an array type:

[array]$temp = $result.data.app.roles.admin | Where-Object -FilterScript {$_.club -ne $ClubNo}
$result.data.app.roles.admin = [array]($temp)