I am writing a function node in node-red that is taking in a JSON object with arbitrary key val pairs:
{ 30000c690b61: "m8Jp_M7Lc0",
30000c290bdc65: "S3qg3Rkl8Y",
30000c290bdf1c: "KsLpfVrR4W",
30000c290be5d0: "oXasuCWV_q",
30000c29e618: "6Q67v-gJkS" … }
I would like to access the first key pair element in this object, store it, and then delete it. I have tried multiple things, but since it is node-red, it seems to behave different
Make any Object array ( req ), then simply do Object. keys(req)[0] to pick the first key in the Object array.
In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method. The value of the key at the first level of the JSON document hierarchy will be obtained.
How do you remove a key value pair from a JSON object? JsonObject::remove() removes a key-value pair from the object pointed by the JsonObject . If the JsonObject is null, this function does nothing.
To remove JSON element, use the delete keyword in JavaScript.
var firstKey = Object.keys(myObject)[0];
delete myObject[firstKey ];
Getting the "first" element of a JSON object expression is difficult, since JSON objects are not intended to be ordered collections. They are "ordered" in JSON only because they must have a string serialization that is an ordered sequence of characters, but two JSON object expressions with differently-ordered properties are meant to convey identical semantics.
If you are willing to trust your JavaScript environment to preserve the ordering of keys when iterating (which is not an assumption defined in the ECMAScript spec, but may be true in your environment's implementation), you can do:
var myObj = JSON.parse("{ ... }");
var firstKey = Object.keys(myObj)[0];
delete myObj[firstKey];
If you do not want to make such an unsafe assumption, you need to read the JSON string and manually determine the key name between the first set of quotation marks. This involves some effort, because you must also handle escaped quotation marks that may appear within the key name itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With