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

时间:2017-06-30 11:45:23

标签: javascript arrays json angular

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

    {
  "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;
                            }
                        }
}
   }

2 个答案:

答案 0 :(得分:1)

非常简单。不要删除想要的但是最后一个,并在要删除的元素后面向后复制一个位置:

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

答案 1 :(得分:1)

在我之前的回答中,我完全忘记了你的需求。

以下代码允许您删除列表中的任何项目(在pristine组件中复制/粘贴它并查看控制台日志):

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

constructor() { }

ngOnInit() {
  this.removeItem('1');
}

removeItem(index: string) {
  let keys = Object.keys(this.list.lists);
  keys = keys.filter(k => k !== index);
  let myNewVar = { selected: null, lists: {} };
  for (let key of keys) { myNewVar.lists[key] = this.list.lists[key]; }
  console.log(myNewVar);
}