javascript - 为什么删除属性时对象索引不重置?

标签 javascript

我试图从数组中删除一些对象:

    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

你要做的事:

  • 转换 objArray通过添加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/

相关文章:

javascript - 如何检查 window.localStorage 是否包含任何值

javascript - jQuery 验证引擎不工作

javascript 用鼠标调整大小

javascript - 如何根据值对映射条目进行排序

javascript - 使用键盘按下打破 JS 中的无限循环

JavaScript : String split() Method only push unique char

JavaScript - 将 HTML 表格数据导出到 Excel

javascript - 获取 twitter 和 google plus 共享计数或任何替代

javascript - 需要合并正则表达式jquery

javascript - Axios POST 请求 : Content-type is set, 但在 spring 内它是空的