gpt4 book ai didi

javascript - 删除数据后更新对象的对象

转载 作者:行者123 更新时间:2023-12-01 03:25:41 25 4
gpt4 key购买 nike

我陷入了需要更新要更新的对象的情况,真正的问题是我想用已删除的项目更新其索引例如:

    {
"selected": null,
"lists": {
"0": [
{
"key": "Survey Meta Data"
}
],
"1": [
{
"key": "Assessment"
}
],
"2": [
{
"key": "Income Survey Process"
}
],
"3": [
{
"key": "Appeal Process"
}
]
}
}

假设我删除了列表[0]:

现在当前的项目将如下所示:

     {
"selected": null,
"lists": {
//"0": [ as deleted so no need just update the others without losing data
// {
// "key": "Survey Meta Data"
// }
//],
"0": [ //now it gets 0
{
"key": "Assessment"
}
],
"1": [//now it gets 1
{
"key": "Income Survey Process"
}
],
"2": [//now it gets 2
{
"key": "Appeal Process"
}
]
}
}

app.js

   function add(data)
{
for (var i=0;i<4;i++)
{

$scope.models.lists[i]=[{"key":data[i].id}]



}
}

function remove(key)
{
for (var i=0;i<$scope.len;i++)
{
for (var s=0;s<$scope.models.lists[i].length;s++)
{


if(key==$scope.models.lists[i][s].key) {
delete $scope.models.lists[i]// deleted now want to update
break;
}
}
}
}

最佳答案

很简单。不要删除最后一个,而是在要删除的元素后面向后复制一个位置:

function remove(key){
var found=false;
var list=$scope.models.lists;
//get the length to properly iterate, requires proper keys e.g. 0,1,2,3
var length=+Object.keys(list).sort().reverse()[0]+1;
//iterate over
for (var i=0;i<length-1;i++){
if(key===list[i][0].key || found) {
//if found override current with next
found=true;
list[i]=list[i+1];
}
}
//delete last one if weve found sth before, or if the last is the one to be deleted
if(list[i][0].key===key || found){
delete list[i];
}
}

http://jsbin.com/casikuxoha/edit?console

或多个:

http://jsbin.com/tewaveyiwa/1/edit?console

关于javascript - 删除数据后更新对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com