Search code examples
jsonnet

Remove duplicates from an array of objects in jsonnet


I have an array of objects, I would like to remove duplicates. My array has a common field name that I would like to use for deduplication.

I am trying to convert the array to a map and then from map back to array but map conversions gives me an error duplicate field name: "a":

local arr = [ 
    { "name": "a", "value": 1234},
    { "name": "b", "value": 555},
    { "name": "c", "value": 0}, 
    { "name": "a", "value": 1234} 
];
local map = { [x.name] : x  for x in arr };

Desired output:

[ 
      { "name": "a", "value": 1234},
      { "name": "b", "value": 555}, 
      { "name": "c", "value": 0} 
]

Solution

  • As @seh pointed out in ksonnet channel, the latest jsonnet release now allows to use std.set() on objects.

     local arr = [
        { name: "a", value: 1234 },
        { name: "b", value: 555 },
        { name: "c", value: 0 },
        { name: "a", value: 1234 },
      ];
     std.set(arr, function(o) o.name)
    

    The std.set() header is documented in jsonnet's std lib implementation.