是否有一个与dicts上的python pop()等效的JavaScript对象? [英] Is there a javascript object equivalent to python's pop() on dicts?
问题描述
我正在寻找与Python的{dict} .pop()等效的JavaScript.我看到JS具有shift()和pop(),但是它们被硬编码为Array中的第一个和最后一个位置.是否可以在其中指定对象的位置?
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?
我可以在Python中做什么的示例:
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}
推荐答案
不是在一条指令中,但是您可以获取属性,然后使用 delete
从对象中删除该属性.
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);
可能有更好的书写方式,欢迎提出建议.(例如,请参见 MartinAdámek的答案,以获得实现相同python语法的不错的实现)
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)
这篇关于是否有一个与dicts上的python pop()等效的JavaScript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!