Thursday, December 28, 2017

CHANGE node - Part 2 - Rule Delete

Probably the easiest operation that can be performed in a Node-RED object is removing (deleting) a property.

Using our "familiar" Node-RED msg object example:









Example #1
Deleting the "mother" property with the following configuration in the Change node:





will result in the following object;






Example #2
Deleting the object msg1 that contains two properties(mother and father):



will result:






Example #3
Deleting the property "grands" that is an array inside the object msg3. This will remove the property and will result in an empty object (as expected).







Example #4
Deleting only one element from an array, let's say we want to delete the property "h" from msg.payload.msg3.grands. We know it is the second element of the array (therefore index 1).


We use:



resulting in:


Notice that the elements of the array were automatically shifted and changed their indexes.


Notice also that the debug tab from Node-RED will show 3 icons when you hover the mouse pointer over an element of the object, like below:




The first icon with symbol >_ will allow you to copy the path of the object to the clipboard. This way you will know exactly what is the object that you are manipulating.

For the above example the path of the 4th element of "grands" is :

payload.msg3.grands[3]


This can be very handy when the structure of the object is complex and large. By checking the path you will know exactly how to refer to the element.



Example #5
Let's say we want to delete the property "w1" from  msg4.ancestors. We better to copy the path as shown before:

Path = payload.msg4.ancestors[0][0]





Then we can safely delete with the proper configuration in the Change node:



Looks like we did not delete the element payload.msg4.ancestors[0][0] ?

We did but the elements of the array have been automatically shifted as expected so payload.msg4.ancestors[0][1] became the new payload.msg4.ancestors[0][0]





Just to close this post let ´s see how we could delete properties without using the Change node.



1 - Refactor the object by iterating over each element, filter the unwanted properties and building a new object (obviously using a function node).

2- Using the "delete" JavaScript statement inside a function node.

3- Setting the value of the property to value "undefined"



I will create a separate post in the future to show how to delete properties programmatically using the function node.

End.