Loading

How to concatenate objects and arrays in DataWeave

Data pubblicazione: Jul 28, 2025
Operazione

GOAL

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.

Fasi

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 ++ obj3
Numero articolo Knowledge

001115009

 
Caricamento
Salesforce Help | Article