Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a javascript object equivalent to python's pop() on dicts? [duplicate]

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}
like image 282
jsamsf Avatar asked Apr 15 '18 23:04

jsamsf


3 Answers

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)

like image 74
Pac0 Avatar answered Oct 21 '22 09:10

Pac0


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);
like image 7
Martin Adámek Avatar answered Oct 21 '22 10:10

Martin Adámek


With a custom function:

function pop(obj, key) {
    var val = obj[key];
    delete obj[key];
    return val;
}
like image 3
beluga Avatar answered Oct 21 '22 11:10

beluga