Inverse map from a property that contains an array

Hi there, I’m trying to figure out a way to reverse a map that includes an array.

For example:

locals {
  sites = {
    a: {domains: ["a.com", "a.net"], id: "site-a"},
    b: {domains: ["b.com", "b.net"], id: "site-b"}
  }
}

What I’d like to produce is transposing each entry in the domains array to a key, containing some of the property of the original object:

{
  "a.com": {id: "site-a"},
  "a.net": {id: "site-a"},
  "b.com": {id: "site-b"},
  "b.net": {id: "site-b"}
}

I’ve been trying various for blocks, splat expressions, and some functions like transform, but I’m having a hard time having both the original object and the domain in scope to be able to do something like {for _, _ in _ : domain => {id: _}}. Any ideas?

I managed to solve this with the merge function the following way:

merge([for site in local.sites : {for domain in site.domains : domain => site}]...)
1 Like

It isn’t exactly what you were asking for, though, but always good to see solutions.