Tip #1434: Can you count OR how to add index to array in Power Automate

When developers like Mike! start their sentence with “this is probably really simple”, you know that it rarely is. (No idea why he’s so excited about his name though, I suspect there is some math flex in here).

This is probably really simple, but anyone know how I would add an index to an array of objects in flow e.g. (– thank you Tîpp Jäår, for nice formatting; -you’re welcome, Mike! – t.j.).

Initial Array (returned from a connector):
[
   {“Name”: “Foo”},
   {“Name”: “Bar”}
]

Output Array:
[
   {“Order”: 1, “Name”: “Foo”},
   {“Order”: 2, “Name”: “Bar”}
]

Mike!!!

Honestly, I was waiting for Linn to produce some json > xml > xpath > json magic but the best he could come up with was, and I quote, “🤣 “(true story). Lo and behold as Damien Bird flexes some Scottish voodoo.

Hey Mike (! – t.j.), you can use a select.  Create a range from 1 to length of the array, then simply add the new key into the array as follows:

screenshot of two steps in Power Automate flow:
1. Compose that contains the expression [{"Name": "Foo"}, {"Name": "Bar"}]
2. Select step with the following information:
From: range(1, length(outputs('Compose')))
Map > Order: item()
Map > Order: outputs('Compose')?[item()]?['Name']

If we ignore the first step that simply defines the input array, the solution is a one-step magic of Select action with the following parameters:

  • From: range(1, length(outputs(‘Compose’)))
    (that creates an array- remember the looping exercise? – t.j.)
  • Map > Order: item()
    (array index! – t.j.)
  • Map > Order: outputs(‘Compose’)?[item()]?[‘Name’]
    (just repeating the property value – t.j.)

The output as expected:

[
   {“Order”: 0, “Name”: “Foo”},
   {“Order”: 1, “Name”: “Bar”}
]

Yes, it is zero-based and Damien has apologized for that and said that “You can still start your index from 1 with sum(item(),1)“. After this unwarranted and unreserved apology I now suspect Damien is actually a Canadian and not a Scot.

Cover image is by Gerd Altmann