Merge objects into first element of the group

Hello All,

I have stumbled upon a scenario where we need to map all the elements within an array to the first element of the object or if we have to simplify the use case based on a certain field we have to merge all the elements together. The examples attached will give more clarity.

Input:

{
	"group": [
		{
			"projectNum": "1234",
			"projectName": "Abc",
			"taskNum": "111",
			"taskName": "Task1"
		},
		{
			"projectNum": "1234",
			"projectName": "Abc",
			"taskNum": "222",
			"taskName": "Task2"
		},
		{
			"projectNum": "1234",
			"projectName": "Abc",
			"taskNum": "333",
			"taskName": "Task3"
		}
	]
}

Output:

{
	"group": [
		{
			"projectNum": "1234",
			"projectName": "Abc",
			"tasks": [
				{
					"taskNum": "111",
					"taskName": "Task1"
				},
				{
					"taskNum": "222",
					"taskName": "Task2"
				},
				{
					"taskNum": "333",
					"taskName": "Task3"
				}
			]
		}
	]
}

Since the projectNum and projectName across all objects will remain the same, we need to merge all the tasks related keys to the first object of the group or reduce the objects in such a way that only one element is left in the array with common project information with the task array attached to that element.

Note: projectNum and projectName will always be common across all the objects in the input array as we are grouping based on projectNum before sending the data to mapper for this specific transformation.

We tried our luck with reduce operation but couldn’t really fetch out a solution, any suggestions on this would be really helpful.

Thank you.

Hey @Tanmay_Sarkar,

Split the Group, and group by projectNum & projectName, and use an expression to filter the objects within the ‘tasks’ array. Here’s an example pipeline:

Merge Objects_2021_11_23.slp (6.3 KB)

Regards

2 Likes

Thanks a lot @bojanvelevski this worked. Tweaked this a bit to get the solution we are looking for.

Another simple way with just 1 mapper expression.

1 Like

Thanks a lot @spinaka, this is really helpful. Gets the job done elegantly only with the help of a mapper.