Consolidating a List of Maps

I have a list of maps as shown

   pet_store = [
        {
            animal_type = "cat"
            animal_name = "fluffy"
        },
        {
            animal_type = "cat"
            animal_name = "blah"
        },
        {
            animal_type = "dog"
            animal_name = "bingo"
        }
    ]

I want to convert that list of maps into this:

pet_store2 = [
        {
            animal_type = "cat"
            animal_name = ["fluffy", "blah"]
        },
        {
            animal_type = "dog"
            animal_name = ["bingo"]
        }
    ]

I’ve tried various for expressions and merge, but I can’t get the correct combination to combine the values as shown. Any guidance would be greatly appreciated.

For situations like this, the grouping behaviour of for expressions is useful. Here’s how to use it:

locals {
  pet_store = [
    {
      animal_type = "cat"
      animal_name = "fluffy"
    },
    {
      animal_type = "cat"
      animal_name = "blah"
    },
    {
      animal_type = "dog"
      animal_name = "bingo"
    }
  ]

  # Convert the list of objects into a map from type to grouped names
  pet_type_names = {
    for entry in local.pet_store: entry.animal_type => entry.animal_name...
  }

  # Generate a sorted list of objects, including type and grouped names
  pet_store2 = [
    for animal_type in sort(keys(local.pet_type_names)): {
      animal_type: animal_type,
      animal_names: local.pet_type_names[animal_type],
    }
  ]
}

The result:

$ echo local.pet_store2 | tf console
[
  {
    "animal_names" = [
      "fluffy",
      "blah",
    ]
    "animal_type" = "cat"
  },
  {
    "animal_names" = [
      "bingo",
    ]
    "animal_type" = "dog"
  },
]
1 Like