Removing a item from object with nested arrays

时间:2019-02-24 03:16:01

标签: javascript angular typescript multidimensional-array

Hi I have object like this

var obj= {
     _id: string;
    name: string;
    loc: [{
         locname: string;
         locId: string;
         locadd: [{
             st: string;
             zip: string;
         }]
     }]
}

Using typescript in angular 2 I want to delete a particular row

deleterow(i, j) {
  // i is index of loc 
  // j is index of locadd
  this.obj.loc.splice(i, 1) //works fine 
  this.obj.loc[i].locadd.splice(j, 1) //doesn't work. I don't get any error just 
  // row is not removed.
}

I am trying solution similar to given in this answer but doesn't work

JavaScript remove item from nested Array

Please let me know how I can remove the an item from locadd Thanks

1 个答案:

答案 0 :(得分:1)

您删除了第i个位置项目。然后,您引用了第i个位置,该位置是已删除位置项的下一个

我认为应该先删除locadd,再删除loc

this.obj.loc[i].locadd.splice(j,1)
this.obj.loc.splice(i, 1)

更新

我做了一个摘要。看来可行。

var obj = {
  loc: [{
    locadd: [{
      st: '1',
      zip: '1',
    },{
      st: '2',
      zip: '2',
    },{
      st: '3',
      zip: '3',
    }]
  }]
};

function deleterow(i, j) {
  // i is index of loc 
  // j is index of locadd
  // this.obj.loc.splice(i, 1) //works fine 
  this.obj.loc[i].locadd.splice(j, 1) //doesn't work. I don't get any error just 
  // row is not removed.
}

console.log(this.obj.loc)
deleterow(0, 1)
console.log(this.obj.loc)