如何更改字典中的所有键但保留值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何更改字典中的所有键但保留值?相关的知识,希望对你有一定的参考价值。
我的代码中有一个字典,例如:
{1:'苹果',2:'葡萄',3:'甜瓜',4:'香蕉',5:'...',6:'...',7:'...'}
现在我正在尝试处理的是从键中删除项目的方式,键不会被中断。
我的意思是:如果我删除2:“'葡萄'”字典键将有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对象不能有数字键(它们被隐式强制转换为字符串)这一事实。
var dict = {
1 : 'a',
2 : 'b',
3 : 'c',
4 : 'd',
5 : 'e'
};//note, that JS objects can't have numeric keys. These will be coerced to strings
function reKeyDict(obj){
var keys = Object.keys(obj);//get an array of all keys;
var len = keys.length;
var greatest = Math.max(...keys);
keys = keys.sort(function(a,b){ return a - b; });
for(i = 1; i <= len; i++){//this needs to change if you want zero based indexing.
if(! keys.includes(i+"")){//we need to coerce to string
//we found a gap
for(var j = i+1, openSlot = i; j <= greatest; j++){
if(obj[j] !== undefined){
obj[openSlot++] = obj[j];
delete obj[j];
}
}
}
}
}
delete dict['3'];
delete dict['4'];
reKeyDict(dict);
console.log(dict);
另一答案
这是一个数组还是一个对象?以下是如何从Object执行此操作,如果它是一个Array,则只需将值部分替换为Array。
宾语:
const obj = { 1: 'a', 2: 'b', 3: 'c' }
const values = Object.values(obj) // [ 'a', 'b', 'c' ]
const newObj = values.reduce((acc, value, i) => {
acc[i+5] = value // replace i+5 with whatever key you want
return acc
}, {})
// {5: "a", 6: "b", 7: "c"}
编辑:糟糕...你的标题“如何更改字典中的所有键但保留值?”和描述希望相反的事情发生。
以上是关于如何更改字典中的所有键但保留值?的主要内容,如果未能解决你的问题,请参考以下文章