首页 > 解决方案 > 如何更改字典中的所有键但保留值?

问题描述

我的代码中有一本字典,例如:

{1:“苹果”,2:“葡萄”,3:“甜瓜”,4:“香蕉”,5:“...”,6:“...”,7:“...”}

现在我要处理的是从这本字典中删除项目,以免键被打断。

我的意思是:如果我删除 2: "'grapes'" 字典键将在 2 应该存在的地方有一个间隙。

我的目标:{1:'苹果',2:'甜瓜',3:'香蕉'4:'...',5:'...',6:'...'}

请记住,每次运行的值都是随机的,因此解决方案不能基于字典中的值。我真的不知道从哪里开始解决这个问题,它一直在弄乱我的脑袋。

我知道将字典变成数组会更容易,但遗憾的是我没有这样做的权限。它必须保留字典。

谢谢你的帮助。

标签: javascriptdictionarykey

解决方案


正如你所说,它真的应该是一个数组。

但是由于您大概知道要删除的索引,因此只需从那里重新编号:

function remove(a, index) {
  while (a.hasOwnProperty(index + 1)) {
    a[index] = a[index + 1];
    ++index;
  }
  delete a[index];
  return a;
}

现场示例:

function remove(a, index) {
  while (a.hasOwnProperty(index + 1)) {
    a[index] = a[index + 1];
    ++index;
  }
  delete a[index];
  return a;
}

const a = {1: 'apples', 2: 'grapes', 3: 'melons', 4: 'bananas'};
console.log("before:", Object.entries(a).join("; "));

remove(a, 2);
console.log("after:", Object.entries(a).join("; "));

请注意,在某些 JavaScript 引擎上,delete对对象使用会显着降低随后对其属性的访问速度。您可以创建一个替换对象:

function remove(a, index) {
  const rv = {};
  let delta = 0;
  for (let n = 1; a.hasOwnProperty(n); ++n) {
    if (n === index) {
      delta = -1;
    } else {
      rv[n + delta] = a[n];
    }
  }
  return rv;
}

function remove(a, index) {
  const rv = {};
  let delta = 0;
  for (let n = 1; a.hasOwnProperty(n); ++n) {
    if (n === index) {
      delta = -1;
    } else {
      rv[n + delta] = a[n];
    }
  }
  return rv;
}

let a = {1: 'apples', 2: 'grapes', 3: 'melons', 4: 'bananas'};
console.log("before:", Object.entries(a).join("; "));

a = remove(a, 2);
console.log("after:", Object.entries(a).join("; "));


但同样,这应该使用为此设计的数据结构:一个数组:

const a = ['apples', 'grapes', 'melons', 'bananas'];
console.log("before:", Object.entries(a).join("; "));

a.splice(1, 1); // Remove the entry at index 1
console.log("after:", Object.entries(a).join("; "));


推荐阅读