top of page
lp.jpeg

Blog

Tags:

Combining Objects: Concatenation in DW 2.0

The video version of this article can be found at the end of the post.



In this post, I will explain what object concatenation is and how to utilize it.


You may be familiar with other language’s concatenation functions, especially when using two strings. For example:


“Hello”.concat(“ World!);
“Hello” + “ World!;
print(“Hello”, “ World!)
Concatenate ‘string “Hello” “ World!

This can also be achieved in DataWeave with the ++ function.


“Hello” ++ “ World”

But, can this also be used for objects? Keep reading to find out!




What is object concatenation?


When I say “object concatenation”, I mean the action of combining 2 different objects, and creating one single object containing all the fields (or keys) and values of these objects.


For example, we have these 2 JSON objects:


key1 value1 key2 key3 value3 key4 value4 key5 key6 value6

And we want to achieve this:


key1 value1 key2 key3 value3 key4 value4 key5 key6 value6

In the end, we have a single object, that contains everything that the other 2 objects had. This is object concatenation.



Object concatenation using ++


The most commonly used way to achieve object concatenation in DataWeave, is the ++ function.


The previous operation, using DW, would look something like this:


dw 2.0 output application json var object1 key1 value1 key2 key3 value3 var object2 key4 value4 key5 key6 value6 object1 plus plus ++ object2

You can see why this is one of the favourites. It’s easy to read and understand. It is very intuitive as well (object1 plus object2).


There is another syntax to do the same thing:


dw 2.0 output application json var object1 key1 value1 key2 key3 value3 var object2 key4 value4 key5 key6 value6 plus plus ++ object1 object2

In this syntax, you are writing the function first, and then positioning the first and second arguments inside parentheses, separated by a comma. Either way is correct; it just depends on what you are used to or what is the standard practice in your project. Both parentheses and ++ do the same thing.



Object concatenation using {( )}


This syntax can be cleaner to see in code, but it can also be a bit confusing for new developers if they’re not familiar with the use of {( )}.