Search code examples
power-automate

power automate iterate over json structure to add counter


I have a json structure in power automate like this:

[
    {
        "title": "doc1.pdf",
        "URL": "someURL"
    },
    {
        "title": "doc1.pdf",
        "URL": "someURL"
    },
    {
        "title": "doc2.doc",
        "URL": "someURL"
    },
    {
        "title": "doc1.pdf",
        "URL": "someURL"
    },
    {
        "title": "doc2.doc",
        "URL": "someURL"
    }
]

I would like to add an element to each dictionary to record the 'count' of the document, so that it ends up like this:

[
    {
        "title": "doc1.pdf",
        "URL": "someURL",
        "count": 1
    },
    {
        "title": "doc1.pdf",
        "URL": "someURL",
        "count": 2
    },
    {
        "title": "doc2.doc",
        "URL": "someURL",
        "count": 1
    },
    {
        "title": "doc1.pdf",
        "URL": "someURL",
        "count": 3
    },
    {
        "title": "doc2.doc",
        "URL": "someURL",
        "count": 2
    }
]

I know this is possible by creating a unique list of 'title' and then iterating over the array for each title and checking for text match, and using a counter variable.

Within that though, how do you actually assign this to a new element in each dictionary in the array?

Thanks in advance for input and for reading.


Solution

  • You can use the addProperty() expression to do exactly that.

    https://learn.microsoft.com/en-us/azure/logic-apps/workflow-definition-language-functions-reference#addproperty

    Mind you, it won’t add it to the item itself, it will create an output that you’ll then need to append to another array variable.

    If you want to do it an easier way, the Advanced Data Operations connector has ways to do what you want without looping.