I wrote the following code to "pop" a property from an object as if it were an array. This looks like the kind of code that would get me slapped by more serious programmers, so I was wondering what is the proper way to do this:
// wrong way to pop:
for( key in profiles ){
var profile = profiles[key]; // get first property
profiles[key] = 0; // Save over property just in case "delete" actually deletes the property contents instead of just removing it from the object
delete profiles[key]; // remove the property from the object
break; // "break" because this is a loop
}
I should have mentioned above, that unlike a true "pop", I don't need the objects to come out in any particular order. I just need to get one out and remove it from its parent object.
Properties in an object are not stored in a stack so the basic concept won't work reliably (aside from the other issues mentioned in the comments above).
If you really need such a construct try something like this.
Demo: http://jsfiddle.net/a8Rf6/5/
You should really declare
key
as avar
.is unnecessary. Delete doesn't touch the value of the property (or in the case of a property that has a setter but no getter, even require that it have a value).
If the object has any enumerable properties on its prototype, then this will do something odd. Consider
A better approach instead of directly modifying the input array. Eg.
You are able to create the pop method like this: .
for some reason using just Object.prototype.pop = function ... breaks JQuery
There's no "correct" order across browsers in what they give for a
for in
loop. Some do them in the order they are put in, other do it numerical indexes first. So there really is no way to do this without creating your own custom objectNowadays you can simply using the spread operator with its Rest way:
const { key, ...profilesWithoutKey } = profiles;
Credit to this blog post