Is there a javascript object equivalent to python pop () on dicts?

I am looking for the JavaScript equivalent of Python {dict} .pop (). I see that JS has shift () and pop (), but they are hardcoded for the first and last positions in the array. Is there an equivalent where I can specify a position for an object?

An 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}
+4
source share
3 answers

Not in one instruction, but you can get a property and then use deleteit to remove the property from the 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);
Run code

So, you can create some custom function that performs these two operations at a time:

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);
Run code

, , . (, . Martin Adámek , python)

+4

:

function pop(obj, key) {
    var val = obj[key];
    delete obj[key];
    return val;
}
+3

I don’t think there is such a thing, also note that shiftboth popare methods arrayand not object.

But you could polyfill 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);
Run code
+2
source

Source: https://habr.com/ru/post/1696203/


All Articles