简体   繁体   English

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

[英]How do I elegantly retrieve and delete an item from a javascript object

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

JSBIN 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 JSBIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM