0

I have list of objects that go with ng-repeat to create a table:

  $scope.fieldData.gridDetails =
   {"1": {
    "Name" : "Test A",
    "Country" : "Germany",
    "City" : "Berlin"
  }, "2": {
    "Name" : "Test B",
    "Country" : "USA",
    "City" : "Chicago"
  }, "3": {
    "Name" : "Test C",
    "Country" : "France",
    "City" : "Paris"
  }, "4": {
    "Name" : "Test D",
    "Country" : "USA",
    "City" : "New York"
  }
  }
});

I want to make a code to remove object, like if I deleted "3": { "Name": "Test C" ... I want it should be:

  $scope.fieldData.gridDetails =
  {"1": {
    "Name" : "Test A",
    "Country" : "Germany",
    "City" : "Berlin"
  }, "2": {
    "Name" : "Test B",
    "Country" : "USA",
    "City" : "Chicago"
  }, "3": {
    "Name" : "Test D",
    "Country" : "USA",
    "City" : "New York"
  }
  }
});

I made this code but its not working:

  $scope.removeItem = function(index){ 
    $scope.fieldData.gridDetails[index] = undefined;
  }

but my code keep it :

  $scope.fieldData.gridDetails =
  {"1": {
    "Name" : "Test A",
    "Country" : "Germany",
    "City" : "Berlin"
  }, "2": {
    "Name" : "Test B",
    "Country" : "USA",
    "City" : "Chicago"
  }, "4": {
    "Name" : "Test D",
    "Country" : "USA",
    "City" : "New York"
  }
  }
});
user1994739
  • 366
  • 4
  • 7

3 Answers3

0
$scope.removeItem = function(index){ 
    $scope.fieldData.gridDetails.splice(index, 1);
}

Try that.

Simon Poole
  • 493
  • 1
  • 6
  • 15
0

Try declaring your $scope.fieldData.gridDetails object as an array like below.

$scope.fieldData.gridDetails =
  [
  {
    "1": {
      "Name": "Test A",
      "Country": "Germany",
      "City": "Berlin"
    }
  },
  {
    "2": {
      "Name": "Test B",
      "Country": "USA",
      "City": "Chicago"
    }
  },
  {
    "3": {
      "Name": "Test C",
      "Country": "France",
      "City": "Paris"
    }
  },
  {
    "4": {
      "Name": "Test D",
      "Country": "USA",
      "City": "New York"
    }
  }
];

then create a function for removing the objects

$scope.removeItem = function(index){
    $scope.fieldData.gridDetails.splice(index,1);
}
Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19
0

To convert the awkward structure to an array:

var x = $scope.fieldData.gridDetails;
var y = Object.keys(x).map(k => x[k]);

Use the form to slice and push the array;

To convert the array back to the awkward structure:

var z = y.reduce((a,x,i) => (a[i+1]=x), {});

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95