Create a list of items that are common between objects

  Kiến thức lập trình

I have these sources of data.(Technically result of some API calls).
The matching logic is Id being equal but notice that it is called different names between the them so Id and AlsoId, IdToo essentially are the same thing

$data1 = @(
    [PSCustomObject]@{ Id='1'; Service='Service1'; Propertyx=1; Price='5' }
    [PSCustomObject]@{ Id='2'; Service='Service1'; Propertyx=1; Price='17' }
    [PSCustomObject]@{ Id='3'; Service='Service1'; Propertyx=1; Price='3' }
    [PSCustomObject]@{ Id='4'; Service='Service1'; Propertyx=1; Price='7' }
)

$data2 = @(
    [PSCustomObject]@{ AlsoId='1'; Service='Service1'; Propertyx=1; Price='5' }
    [PSCustomObject]@{ AlsoId='2'; Service='Service1'; Propertyx=1; Price='17' }
    [PSCustomObject]@{ AlsoId='5'; Service='Service1'; Propertyx=1; Price='3' }
    [PSCustomObject]@{ AlsoId='6'; Service='Service1'; Propertyx=1; Price='7' }
)

$data3 = @(
    [PSCustomObject]@{ IdToo='1'; Service='Service1'; Propertyx=1; Price='5' }
    [PSCustomObject]@{ IdToo='2'; Service='Service1'; Propertyx=1; Price='17' }
    [PSCustomObject]@{ IdToo='5'; Service='Service1'; Propertyx=1; Price='3' }
    [PSCustomObject]@{ IdToo='7'; Service='Service1'; Propertyx=1; Price='7' }
)

I want to create a new object just to keep the Ids that are common between all three. So in this example the result should include only “1” and “2” because they exist in all three of them.

I tried to get some ideas to adapt from this post: How to get the “difference” between two objects in another object with the same structure using powershell?
but it didn’t go far. How can I achieve this in an efficient manner.

LEAVE A COMMENT