arrays - 重枚举索引 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 + ')');
}
}
解决方案
使用任何编程语言,使用 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 开始计数。
推荐阅读
- distributed-computing - 没有领导下台的领导连任?
- reactjs - 如何在反应中使用纯 flatpickr?
- c# - Xamarin 表单中的 CoreBluetooth iOS API
- laravel - 几个带有“OR”条件的验证规则
- java - Tomcat 8 在方法名称中发现无效字符。HTTP 方法名称必须是标记
- angular - 带有特殊字符的 angular-l10n 奇怪的翻译
- php - 如何在 laravel 中使用附加方法使用关系
- swagger - Swagger YAML 规范,有条件的必填字段
- python - 如何在 Python 中动态引用变量?
- javascript - 电子:总是返回 ontouchstart = true