我想使用其键返回一个项目,同时删除它。有没有一种优雅的方法来实现这一目标?
不雅的解决方案
const popItem = (key) => {
const popped = items[key]
delete items[key]
return popped
}
答案 0 :(得分:1)
你为什么不试着改变它?
const popItem = (obj, key) => {
{ [key], ...rest } = obj;
return { popped: key, newObj: rest };
};
然后你可以这样称呼它:
const { popped, newObj } = popItem(obj, key);
答案 1 :(得分:1)
这个怎么样?
const items = {1: 'one', 2: 'two'}
const popItem = (obj, key) => [obj[key], delete obj[key]][0];
console.log(popItem(items, 2)); // 'two'
console.log(items); // { 1: 'one; }
或者如果你想从函数中返回新的obj:
const items = {1: 'one', 2: 'two'}
const popItem = (obj, key) => [obj[key], [delete obj[key], obj][1]];
const [newObj, item] = popItem(items, 1);
console.log(newObj) // 'one'
console.log(item) // { 2: "two" }