Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "pop" from object

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.

like image 802
Chris Dutrow Avatar asked Jul 08 '11 21:07

Chris Dutrow


2 Answers

Nowadays you can simply use the spread operator with its Rest way:

const { key, ...profilesWithoutKey } = profiles; 

Credit to this blog post

like image 95
Noam Gal Avatar answered Sep 24 '22 02:09

Noam Gal


for( key in profiles ){ 

You should really declare key as a var.

profiles[key] = 0;            // Save over property just in case "delete" actually deletes the property contents instead of just removing it from the object 

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

Object.prototype.foo = 42;  function take(obj) {   for (var key in obj) {     // Uncomment below to fix prototype problem.     // if (!Object.hasOwnProperty.call(obj, key)) continue;     var result = obj[key];     // If the property can't be deleted fail with an error.     if (!delete obj[key]) { throw new Error(); }     return result;   }  }  var o = {}; alert(take(o));  // alerts 42 alert(take(o));  // still alerts 42 
like image 31
Mike Samuel Avatar answered Sep 20 '22 02:09

Mike Samuel