我有一张地图
const myMap = new Map();
myMap.set("10/10", 0);
myMap.set("10/11", 1);
myMap.set("10/12", 2);
myMap.set("10/13", 3);
myMap.set("10/14", 4);
,我需要按键删除一项,并更新下一项的所有值。
例如,如果我删除键为"10/12"的项目,映射必须是:
console.log(myMap);
/*
{
"10/10": 0,
"10/11": 1,
"10/13": 2,
"10/14": 3,
}
*/
减少>将删除的项值减去1。什么好主意吗?
应该这样做:
const obj = {
"10/10": 0,
"10/11": 1,
"10/12": 2,
"10/13": 3,
"10/14": 4,
}
const toRemove = "10/12"
let i = 0;
const newObj = {}
for(const property in obj){
if(obj.hasOwnProperty(property) && property !== toRemove){
newObj[property] = i;
i++;
}
}
console.log(newObj);
编辑:
使用Map的版本:
const obj = new Map();
obj.set("10/10", 0);
obj.set("10/11", 0);
obj.set("10/12", 0);
obj.set("10/13", 0);
obj.set("10/14", 0);
const toRemove = "10/12";
let i = 0;
const newObj = new Map();
for(let [key, value] of obj){
if(key !== toRemove){
newObj.set(key, i);
i++;
}
}
newObj.forEach((value, key) => console.log(key + ": " + value));
你把它分成如下几个阶段:
const obj = {
"10/10": 0,
"10/11": 1,
"10/12": 2,
"10/13": 3,
"10/14": 4,
}
const key = "10/12";
const index = Object.keys(obj).findIndex(k => k === key);
const entries = Object.entries(obj);
const values = Object.values(obj).slice(index, -1);
entries.splice(index, 1);
const res = entries.reduce((acc, [key, value], i) => {
if(i >= index) {
acc[key] = values[0];
values.shift();
} else {
acc[key] = value;
}
return acc;
}, {})
console.log(res)