Reputation: 4923
I need to be able to add an element to an arbitrarily complex object using JSONata.
I don't know all the elements in the object in advance.
For example, lets say I want to add
"newElement": { "a": 1, "b": 2 }
To an object that looks like:
{ "xx": "An", "yy": "Example", "zz": 1 }
But it might have any number or mix of other elements.
I can replace the whole object but I can't work out how to add to it.
Upvotes: 3
Views: 7045
Reputation: 1549
Starting with JSONata 1.3, you can use the $merge
function to do this. See example here.
Upvotes: 5
Reputation: 1121
Here is one technique that I have used to merge two objects...
Split all the object keys/values into an array of pairs and build a new object:
$zip(*.$keys(), *.*) { $[0]: $[1] }
Note that this requires a single input object which contains the old and new objects in separate fields. (actually, since the $keys() function can operate on an array of objects, you are not limited to only two objects -- in fact, it could be an array of objects instead of separate fields -- your mileage may vary)
{ "newObject": { "a": 1, "b": 2 }, "oldObject": { "xx": "An", "yy": "Example", "zz": 1, "b": 3 } }
Also, the order of the two objects matters, since the first unique key value will take precedence. For instance, if the newObject is first, and both objects contain field "b", the output value will be used from the first object (effectively overwriting the oldObject value for "b"). So the merged output object is:
{ "a": 1, "b": 2, "xx": "An", "yy": "Example", "zz": 1 }
Upvotes: 3