How to remove last key:value pair in JavaScript

Tags: ,



I am very new to JavaScript and I am trying to figure out how to set a function to remove the last key:value pair to the right, much like array.pop for an array. This is an assignment I am working on. It seems confusing to me because, from my limited understanding of JS their is no specific order in a list of properties in an object. If anyone has any insight I would appreciate it. Here is the object:

var array = {length:0, size:big, smell:strange};

this is where I have started to go, but just having a hard time completing the function:

array.pop = function() {
//...
};

Ultimately I would like it to turn out like this:

array = {length:0, size:big};    

Thanks in advance.

Answer

Objects do not have any defined order of properties so there is no “last” property. You have to remove a property by name, not position.

You can, of course, iterate over the properties and inspect them as you iterate and decide whether you want to delete any given property by looking at its name. Some javascript implementations will preserve the order that properties were added, but that is specifically not guaranteed by the ECMAScript specification so it cannot be relied upon.



Source: stackoverflow