-1

How can I map an array of objects with the same keys to subsequent keys with an incrementing integer as its postfix?

Input:

[
    {
        "test1": {},
        "test1": {}
    },
    {
        "test2": {},
        "test2": {}
    }
]

The above input receiving and expected output would be as below like each object set supposed to contain different combination of keys like (test1 and test2)

Expected Output:

[
    {
        "test1": {},
        "test2": {}
    },
    {
        "test1": {},
        "test2": {}
    }
]
Skully
  • 2,882
  • 3
  • 20
  • 31
SP-
  • 37
  • 6

1 Answers1

1

If we assume that all the elements have the same keys in the same order we can get all the keys then map each object in the array. Each element of the array is an object, we can use mapObject() to replace the keys by the list of keys.

%dw 2.0
output application/json
fun getKeys(a:Array)=a reduce ((item,acc=[])->acc << namesOf(item)[0])
var allKeys=getKeys(payload)
---
payload map ($ mapObject ((value, key, index) -> (allKeys[index]):value))

Output:

[
  {
    "test1": {
      
    },
    "test2": {
      
    }
  },
  {
    "test1": {
      
    },
    "test2": {
      
    }
  }
]
aled
  • 21,330
  • 3
  • 27
  • 34