首页 > 解决方案 > 重枚举索引 JSON

问题描述

我将数据存储在 JSON 中 - 其中一个字段是一个索引,它确定其他数据的完成顺序。想象

 [
    {
    “Action” : “Wake up”,
    “id” : 1
    },
    {
    “Action” : “Make coffee”,
    “id” : 2
    },
    {
    “Action” : “Check Email”,
    “id” : 3
    }
   ]

问题是,如果我想在列表中包含一个额外的项目 - 我必须手动重新输入所有索引。例如,如果我决定我应该插入

{
“Action” : “Feed Cat”,
“id” : 2
}

那么所有较低的指数都是错误的。

是否有可以自动重新编号的工具,以便 id 字段始终是连续的 1、2、3、4、5,但是我移动了数据项?

有一个添加插件脚本的选项 - 示例如下 - 但我不知道 JavaScript,所以我无法清楚地看到如何编辑它以进行我想要的批量编辑

PJEPlugIn = {        
JSON processing function, will take two arguments                                                          @param json    JSON object from editor, maybe null for inform JSON      @param jsonStr JSON text from editor     
@return Return value can be any valid JavaScript object, string will be treated as JSON text      */     
func: function(json, jsonStr) {         
return eval('(' + jsonStr + ')');    
 } 
}

标签: arraysjson

解决方案


使用任何编程语言,使用 java 脚本,使用Array.splice

let data = [{
    "Action": "Wake up",
    "id": 1
  },
  {
    "Action": "Make coffee",
    "id": 2
  },
  {
    "Action": "Check Email",
    "id": 3
  }
];
let item = { "Action" : "Feed Cat", "id" : 2 }
// with Array.splice() method
// 1st argument is insertion index (start)
// 2nd delete count
// 3nd insertion item
data.splice(1, 1, item);

console.log(data)

注意:在计算中,索引从 0 开始计数。


推荐阅读