javascript - 如何更改字典中的所有键但保留值?
问题描述
我的代码中有一本字典,例如:
{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("; "));
推荐阅读
- ansible - 在 Ansible 中使用 expect 并在 Shell 模块中发送时发送无法正常工作
- css - iOS Safari 上的 Vue Carousel 仅适用于第一张幻灯片
- python - 如何在 python 中绘制 23h-25h 时间序列
- javascript - 在网络摄像头视频上运行poseNet时出错
- scikit-learn - 在 scikit-learn 的两列上使用分层训练测试数据拆分
- reporting-services - 如何在SSRS中每2行背景颜色后交替行
- powershell - 如何处理powershell脚本块中的引号
- java - 用 Java 编写响应处理程序
- python - Scipy中的“冻结分布”是什么意思?
- email - 设置 DNS 的推荐方法?