jsonnet std.mapWithKey - not generating an array?

1.9k Views Asked by At

I have a local jsonnet object defined as so:

local compactRules = {
  key1: "val1",
  key2: "val2",
  key3: "val3"
};

And I'd like to generate this array:

[
  {
    rule: "key1",
    action: "val1",
  },
  {
    rule: "keyk2",
    action: "val2"
   }
  // ...
]

And I'm surprised std.mapWithKey didn't deliver. The docs don't mention anything about the output format and I'm still confused about it's behavior:

std.mapWithKey(function(key_name, value) {
  rule: key_name,
  action: value
}, compactRules)

Yields:

{
   "key1": {
      "action": "val1",
      "rule": "key1"
   },
   "key2": {
      "action": "val2",
      "rule": "key2"
   },
   "key3": {
      "action": "val3",
      "rule": "key3"
   }
}

Why does it use the original keys in the resulting object, if I already handle the keys my self in the function?

I wouldn't have been so dissatisfied, unless there was a std.objectValues function, that could have returned only the values of all fields, as an array - i.e the array I'm interested in.

2

There are 2 best solutions below

0
On

This is what you need:

std.map(function(key_name) {
  rule: key_name,
  action: compactRules[key_name],
}, std.objectFields(compactRules))

Though it seems others have notice the lack of this functionality in https://github.com/google/jsonnet/issues/543 .

0
On

My use case is a reversed one. Here's an example:

local f(a,o) = a + [{[o.id]:o.price}];
local arr = [{id:'foo', price:'high'},{id:'bar', price:'low'}];
std.foldl(f, arr, [])