1

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
}
biofractal
  • 18,963
  • 12
  • 70
  • 116
  • Have a look at this discussion. I think you need to stay inelegant http://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object – mplungjan Nov 30 '16 at 09:42

2 Answers2

1

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);
Alberto Centelles
  • 1,215
  • 11
  • 24
1

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; }

JSBIN

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" }

JSBIN

Rotareti
  • 49,483
  • 23
  • 112
  • 108