我的代码中有一本字典,例如:
{1:“苹果”, 2:“葡萄”, 3:“瓜”, 4:“香蕉” 5: '...', 6: '...', 7: '...'}
现在我正在尝试处理的是从该字典中删除项目,并且键不会被中断。
我的意思是:如果我删除 2: "'grapes'"字典键将在 2 应该在的位置有一个间隙。
我的目标: {1:“苹果”, 2:“瓜”, 3:“香蕉” 4: '...', 5: '...', 6:'...'}
请记住,每次运行的值都是随机的,因此解决方案不能基于字典中的值。 我完全不知道从哪里开始解决这个问题,它一直困扰着我。
我知道将字典转换为数组会更容易,但遗憾的是我没有这样做的权限。它必须是一本字典。
感谢您的帮助。
最佳答案
正如你所说,它确实应该是一个数组。
但是由于您可能知道要删除的索引,因此只需从那里重新编号即可:
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("; "));
关于javascript - 如何更改字典中的所有键但保留值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52206857/