I would like to return an item using its key and delete it at the same time. Is there an elegant way to achieve this?
Inelegant Solution
const popItem = (key) => {
const popped = items[key]
delete items[key]
return popped
}
I would like to return an item using its key and delete it at the same time. Is there an elegant way to achieve this?
Inelegant Solution
const popItem = (key) => {
const popped = items[key]
delete items[key]
return popped
}
Why don't you try not to mutate it?
const popItem = (obj, key) => {
{ [key], ...rest } = obj;
return { popped: key, newObj: rest };
};
And then you can call it like this:
const { popped, newObj } = popItem(obj, key);
How about this?
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; }
Or if you want to return the new obj from the function as well:
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" }