我试图从数组中删除一些对象:
obj = {
"0":{
test: "test",
test: "test"
},
"1": {
test1: "test1",
test1: "test1"
},
"2": {
test2: "test2",
test2: "test2"
}
}
如果我删除类似的项目
delete obj[1];
我确实得到以下信息:
obj = {
"0":{
test: "test",
test: "test"
},
"2": {
test2: "test2",
test2: "test2"
}
}
但是我希望 obj 的索引为 0 和 1。因为很奇怪,如果我询问结果的 .length(删除该项目后),它会给我 3,而我需要其余部分的正确长度应用程序的。
我意识到这是一个重复的问题(实际上是伪造的),但我正在寻找的问题从未得到解答。我想它的行为方式如此?有没有办法重置索引?
最佳答案
您的obj
看起来像 Array
但不是Array
。
你要做的事:
- 转换
obj
至Array
通过添加length
属性并使用 ES6 的 Array.from(obj) - 使用
Array.splice
删除数组中的项目。 - 转换
Array
返回json object
通过Array.forEach
查看此代码片段。
var obj = {
"0": {
test: "test",
test: "test"
},
"1": {
test1: "test1",
test1: "test1"
},
"2": {
test2: "test2",
test2: "test2"
},
"length": 3
};
// method of ES5
//var arr1 = [].slice.call(obj);
// method of ES6
var arr1 = Array.from(obj);
console.log(arr1);
//delete arr1[1];
arr1.splice(1, 1);
console.log(arr1);
console.log(arr1.length);
// convert back to json
obj = {};
arr1.forEach(function(item, index) {
obj[index] = item;
});
console.log(obj);
关于javascript - 为什么删除属性时对象索引不重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221221/