How can I efficiently remove a key from an object?
-
"delete" does not work as expected:
There are some methods to iterate over the keys in the object and remove one and return a copy of the original, but that seems a little excessive and painful for that task at hand. Is there something simple like "delete"?
-
So this works but it's just a little clunky:
var testObject = {"testKey1": "testValue1", "testKey2": "testValue2"}; // removes a key from an object, but just be aware that it does not edit the object in place // you must use the new object made here to replace the original inline function objectRemoveKey(obj, keyToRemove) { local newObj = {}; for (key in obj) { if (key != keyToRemove) { newObj[key] = obj[key]; } } return newObj; } var testRemove = objectRemoveKey(testObject, "testKey1"); Console.print(trace(testRemove));
-
@VirtualVirgin You can't, as you've discovered you have to recreate the object. I usually just set the value to
undefined
instead. -
@d-healey can it be done in plain JS? I can clone that syntax and add it in HiseScript, as this is actually a valid request.
-
Haha so yeah delete key is the syntax, but that feels somewhat weird…
-
@Christoph-Hart Maybe make it match the array remove method.
-
@d-healey yeah something like
JSON.delete(obj, key)
is the easiest way, thedelete
syntax would require a real brain-twister with the current parser.