cancel
Showing results for 
Search instead for 
Did you mean: 

Adding items to a nested list

dkollar
Deputy Chef I
Deputy Chef I

Hello,

I have a recipe that pulls data by a specified date range. 

Sample data parsed from a list variable:

 

{
  "data": [
    {
      "Id": "1234",
      "Items": 
        {
          "Item": "Placeholder Item"
        }
    },
    {
      "Id": "1234",
      "Items": 
        {
          "Item": "Placeholder Item 2"
        }
    },
      "Id": "5678",
      "Items": 
        {
          "Item": "Placeholder Item"
        }
    },
    {
      "Id": "5678",
      "Items": 
        {
          "Item": "Placeholder Item 2"
        }
    },
  ]
}

 

What I would like is to format the data in this way:

 

{
  "data": [
    {
      "Id": "1234",
      "Items": [
          "Placeholder Item",
          "Placeholder Item 2"
        ]
    },
    {
      "Id": "5678",
      "Items": [
          "Placeholder Item",
          "Placeholder Item 2"
        ]
    }
  ]
}

 

I want any Items that have the same Id to be combined under a single Id. Any ideas how this can be done?

1 ACCEPTED SOLUTION

gary1
Executive Chef III
Executive Chef III

You can do this in a Ruby action using the below code. This way you don't have to loop through your array and burn a whole lotta tasks :

data = []
records = input["array"]
ids = input["array"].pluck('Id').uniq

ids.each { | id |
obj = {}
items = []
records.each { | record |
if record["Id"] == id
items.push(record["Items"]["Item"])
end
}
obj["Id"] = id
obj["Items"] = items
data.push(obj)
}

{data: data}

Parse your JSON input first and then set up the Ruby action like this:

gary1_0-1677793494003.png

Output:

gary1_3-1677793704537.png

gary1_1-1677793549466.png

 

 

View solution in original post

1 REPLY 1

gary1
Executive Chef III
Executive Chef III

You can do this in a Ruby action using the below code. This way you don't have to loop through your array and burn a whole lotta tasks :

data = []
records = input["array"]
ids = input["array"].pluck('Id').uniq

ids.each { | id |
obj = {}
items = []
records.each { | record |
if record["Id"] == id
items.push(record["Items"]["Item"])
end
}
obj["Id"] = id
obj["Items"] = items
data.push(obj)
}

{data: data}

Parse your JSON input first and then set up the Ruby action like this:

gary1_0-1677793494003.png

Output:

gary1_3-1677793704537.png

gary1_1-1677793549466.png