Search

Dark theme | Light theme

February 23, 2022

DataWeave Delight: Reversing order of keys in objects

An object in DataWeave consists of key and value pairs. If we want to create a new object sorted by key or value we can use the orderBy function from the dw::Core module. The orderBy function takes as first argument the object. The second argument is a criteria function that can the value and key to determine how to order the object. But if we want to reverse the ordering of the key and value pairs we cannot simply use the orderBy function, because we don't have access to the index value of the key/value pair in the criteria function. We would love to have that index value, so we could negate the index value to reverse the ordering. What we need to do is first turn our object in an array of objects using the pluck function, where each object has our key and value. We can now use the orderBy function on that array of objects to reverse the order. Finally we need to reduce the array of objects into a new object using the reduce function, where the ordering of keys will be reversed.

In the following example we use :

Source

%dw 2.0

var object = {
    name: "Hubert Klein Ikkink",
    alias: "mrhaki",
    city: "Tilburg"
}

output application/json
---
{
    reverseKeys: object 
        // Turn into array: [{name: "Hubert Klein Ikkink"}, ...]
        pluck ((value, key, index) -> {(key): value})

        // Reverse the ordering based on negated index value
        orderBy ((item, index) -> -index) 

        // Transform array back to an object.
        reduce ((item, accumulator = {}) -> accumulator ++ item)
}

Output

{
  "reverseKeys": {
    "city": "Tilburg",
    "alias": "mrhaki",
    "name": "Hubert Klein Ikkink"
  }
}

Written with DataWeave 2.4.