如何从javascript对象中优雅地检索和删除项目

时间:2021-10-12 15:14:22

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
}

2 个解决方案

#1


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:

或者如果你想从函数中返回新的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" }

JSBIN

#2


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

#1


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:

或者如果你想从函数中返回新的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" }

JSBIN

#2


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