Remove fields (the key property) that have value null in an array aggregation

My goal is to create an array that has the structure like below. Where the properties pet_name, pet_image, etc are not present when there is no value for it

What I am doing right now:

  1. Iterating over each line item in a Shopify order and finding all (relevant) metafields
  2. For each line item aggregate those metafields
  3. For each line item aggregation of metafields create a JSON
  4. Parse that JSON
  5. Aggregate into one array where each item in the array represents one line item

If a line item has metafields for pet name, pet image etc then they should be included in the output array. If there are no metafields only the ID should be in the array.

The API I am sending this to will not accept that I pass “pet_name”: null for example.

How can I remove the property names that are empty/null in the array?

Here is the expected array structure:

[
    {
        "array": [
            {
                "id": "13048987058199",
                "pet_name": "Lacy",
                "pet_image": "https://cdn.shopify.com/s/files/1/...0001.jpg",
                "pet_image2": "https://cdn.shopify.com/s/files/1...0001.jpg",
                "product_uid": "",
                "template_id": "d8b055b1-3950-48e4-abbd-9fab912ec936",
                "template_variant_id": ""
            },
            {
                "id": "13048987090967",
                "pet_name": "Comet",
                "pet_image": "https://cdn.shopify.com/s/files/...0999.jpg",
                "pet_image2": "https://cdn.shopify.com/s/...0999.jpg",
                "product_uid": "",
                "template_id": "d8b055b1-3950-48e4-abbd-9fab912ec936",
                "template_variant_id": ""
            },
            {
                "id": "13048987123735"
            }
        ],
        "__IMTAGGLENGTH__": 3
    }
]