jsonnet

How can I nest Jsonnet object comprehensions and run the inner loop a different number of times?


I'm trying to figure out how to nest/chain an object comprehension to do something other than a 'full product' and have the inner loop iterate a different amount, but can't figure it out.

{
    ["%s-thing-%i" % [grp.name, n]]: {
        name: grp.name,
        // a bunch of other stuff I don't want to repeat
    }
    // for n in std.range(1, grp.count)  // invalid, 'Unknown variable: grp'
    for n in std.range(1, 3)
    for grp
    in [{name: "foo", count: 2}, {name: "bar", count: 4}]
}

I want a one-level object with two foo-thing-s and four bar-thing-s, but I can't use the count object property like on my commented line as at that point grp is not defined.


Solution

  • Below snippet seems to implement what you need, without the flatMap() transform "in the middle":

    source

    local input = [{ name: 'foo', count: 2 }, { name: 'bar', count: 4 }];
    {
      ['%s-thing-%i' % [entry.name, n]]: { name: entry.name }
      for entry in input
      for n in std.range(1, entry.count)
    }
    

    output

    {
       "bar-thing-1": {
          "name": "bar"
       },
       "bar-thing-2": {
          "name": "bar"
       },
       "bar-thing-3": {
          "name": "bar"
       },
       "bar-thing-4": {
          "name": "bar"
       },
       "foo-thing-1": {
          "name": "foo"
       },
       "foo-thing-2": {
          "name": "foo"
       }
    }