When we try to concatenate objects and arrays in DataWeave we can get coercion errors if some objects are composed by arrays. The goal is to do it effectively into a new one.
Given the following definitions in DataWeave:
%var obj1 = {a: 1}
%var arr1 = [1, 2, 3, 4]
%var obj2 = {a: 11, b: {c: "xyz", d: [1, 2, 3, 4]}}
%var obj3 = {a: 1, d: [1, 2, 3, 4]}
If we want to concatenate all the objects into a new object, the following expression produces a coercion error:
{
(obj1),
arr1: (arr1),
(obj2),
(obj3)
}
The expression inside parenthesis in an object should return an array of objects. Sometimes because of some auto coercions objects also work, but the correct is that should return an array of objects.
Whenever we apply the {( )}, it essentially reduces all elements by trying to concatenate all elements together as objects, hence when we try to concatenate an object with an array we get the "cannot coerce array to object" error.
If we want to concatenate all the objects we should use the concat operator ++ in this way:
%dw 1.0
%output application/dw
%var obj1 = {a: 1}
%var arr1 = [1, 2, 3, 4]
%var obj2 = {a: 11, b: {c: "xyz", d: [1, 2, 3, 4]}}
%var obj3 = {a: 1, d: [1, 2, 3, 4]}
---
obj1 ++ {arr1: arr1} ++ obj2 ++ obj3001115009

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.