Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first key pair element of JSON object without knowing key and deleting it in node red

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

like image 257
Sharon Soleman Avatar asked Feb 07 '17 18:02

Sharon Soleman


People also ask

How do I get the first element of a JSON object?

Make any Object array ( req ), then simply do Object. keys(req)[0] to pick the first key in the Object array.

How do I get key-value pairs in JSON?

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?

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.

How do you remove an element from a JSON object?

To remove JSON element, use the delete keyword in JavaScript.


2 Answers

var firstKey = Object.keys(myObject)[0];
delete myObject[firstKey ];
like image 140
Vladu Ionut Avatar answered Oct 18 '22 01:10

Vladu Ionut


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.

like image 34
apsillers Avatar answered Oct 18 '22 01:10

apsillers