I'm looking for a JavaScript equivalent of Python's {dict}.pop(). I see that JS has a shift() and pop(), but those are hardcoded for first and last positions in an Array. Is there an equivalent where I can specify the position for an Object?
Example of what I can do in Python:
>>> foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4}
>>> player = foxx.pop('player')
>>> foxx
{'date': '2018-01-01', 'homeruns': 3, 'hits': 4}
>>> player
{'name': 'Jimmie', 'last': 'Foxx', 'number': 3}
Not in one instruction, but you can get the property and then use delete
to remove the property from an object.
let foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4};
let player = foxx.player;
delete foxx.player;
console.log(foxx);
console.log(player);
So you could create some custom function that does these two operations in one go :
function pop(object, propertyName) {
let temp = object[propertyName];
delete object[propertyName];
return temp;
}
let myObj = { property1 : 'prop1', property2: 'prop2' };
let test = pop(myObj, 'property1');
console.log(myObj);
console.log(test);
There is probably a better way of writing this, suggestions welcome. (for instance, see Martin Adámek's answer for a nice implementation leading to the same python syntax)
I do not think there is such a thing, also note that shift
and pop
are methods of array
, not of an object
.
But you could polyfill that yourself easily:
Object.defineProperty(Object.prototype, 'pop', {
enumerable: false,
configurable: true,
writable: false,
value: function (key) {
const ret = this[key];
delete this[key];
return ret;
}
});
var foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4}
var player = foxx.pop('player')
console.log(foxx, player);
With a custom function:
function pop(obj, key) {
var val = obj[key];
delete obj[key];
return val;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With