Javascript "pop" from object

Viewed 77004

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.

8 Answers

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

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

Credit to this blog post

Having studied all the comments and solutions above, I can offer a completely ready solution based on them:

Object.prototype.pop = function() {
    for (var key in this) {
        if (!Object.hasOwnProperty.call(this, key)) continue;
        var result = this[key];
        if (!delete this[key]) throw new Error();
        return result;
    }
};

var obj = {
    a: '1',
    b: '2',
    c: '3'
};

console.log(obj.pop()); // 1
console.log(obj.pop()); // 2
console.log(obj.pop()); // 3
console.log(obj); // Object {  }

Perhaps someone will come in handy ; )


PS. If you use the code I propose along with the jQuery library, you may encounter errors in the console. In this case, the option given below is appropriate:

function _pop() {
    for (var key in this) {
        if (!Object.hasOwnProperty.call(this, key)) continue;
        if (key === 'pop') continue;
        var result = this[key];
        if (!delete this[key]) throw new Error();
        return result;
    }
}

var obj = {
    a: '1',
    b: '2',
    c: '3'
};

obj.pop = _pop;

console.log(obj.pop()); // 1
console.log(obj.pop()); // 2
console.log(obj.pop()); // 3
console.log(obj); // Object { pop: _pop() }

Thus without loop and "function" noise, simply

key = 'b'
profile = {a:1, b:2, c:3}

val = profile[key] 
delete profile[key]

console.log(profile, key, val)   // Object { a: 1, c: 3 } b 2

Or, with dynamic key unpacking following the comment from @hellopeach

profile = {a:1, b:2, c:3}
key = 'b'
var {[key]: val, ...profile} = profile
// var {b: val, ...profile} = profile 

console.log(profile, key, val)   // Object { a: 1, c: 3 } b 2

Related