Search code examples
jqueryfilter

How to delete values in json-jquery-array?


My PHP file returned a JSON array full of values.

$positions = array();
while ($row = mysqli_fetch_assoc($abfrage)) {
    array_push(
        $positions,
        array(
            'posID' => $row['posID'],
            'pos1' => $row['pos1'],
            'pos2' => $row['pos2']
        )
    );
}

@mysql_close($connection);
echo json_encode(array("positions" => $positions));
exit; 

Now in my js-File, I want to delete a data set where posID == x for example, but I don't know how to do it

$.each(positions, function(i, v) {
  if (v.posID == id) {
    ... delete data set ...
  }
});

Solution

  • Create a new array with the items that you want to keep:

    var result = $.grep(positions, function(v){
      return v.posID != id;
    });