-1

I am trying to get a json .Which row has a null value I want to delete it using javascript. Suppose my json is like

 [{
     "unit_id": "9",
     "CHGRAPHUpdatetime": {
         "time": "2018-03-15 00:00:00"
     },
     "channelGraph": [{
         "chkey": "ch1",
         "list": "1"
     }, {
         "chkey": null,
         "list": null
     }]
 }]

If chkey and chvalue is null then row will be deleted.

Expected result is

[{
    "unit_id": "9",
    "CHGRAPHUpdatetime": {
        "time": "2018-03-15 00:00:00"
    },
    "channelGraph": [{
        "chkey": "ch1",
        "list": "1"
    }]
}]

Could you please help me to resolve this problem.

Andreas
  • 21,535
  • 7
  • 47
  • 56
Priya
  • 31
  • 6
  • That's not [JSON](http://json.org). _"JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML."_ - [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Apr 09 '18 at 11:51
  • Please share your attempt. – gurvinder372 Apr 09 '18 at 11:53

2 Answers2

0

Assuming you've serialised your JSON into a JavaScript object:

var my_array = [{
  "unit_id": "9",
  "CHGRAPHUpdatetime": {
    "time": "2018-03-15 00:00:00"
  },
  "channelGraph": [{
    "chkey": "ch1",
    "list": "1"
  }, {
    "chkey": null,
    "list": null
  }]
}];

document.write("<pre>" + JSON.stringify(my_array) + "</pre>");

for (var i = 0; i < my_array.length; i += 1) {
  var rows = my_array[i].channelGraph;
  for (var j = 0; j < rows.length; j += 1) {
    if (rows[j].chkey === null && rows[j].chkey === null) {
      rows.splice(j, 1); // Removes one row at index j
      j -= 1; // Avoid skipping a row - 
              // we want the next row to be next.
    }
  }
}

document.write("<pre>" + JSON.stringify(my_array) + "</pre>");
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
0

Try this :

var obj =  [{
     "unit_id": "9",
     "CHGRAPHUpdatetime": {
         "time": "2018-03-15 00:00:00"
     },
     "channelGraph": [{
         "chkey": "ch1",
         "list": "1"
     }, {
         "chkey": null,
         "list": null
     }]
 }];
 
 obj[0].channelGraph.filter((item, index) => {
     (!item.chkey && !item.list) ? obj[0].channelGraph.splice(index, 1) : '';
 });
 
 console.log(obj);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123