Announcement

Collapse
No announcement yet.

delete of JSON msg object results in null

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • delete of JSON msg object results in null

    I use this to remove certain object from a JSON message received.
    Code:
    for (i=0; i < msg.results.length; i++) {
       if(msg.results[i].PMT != '1'){
       	delete msg.results[i];
       }  
    }
    It does indeed remove the object but it leave a null,in the message like this:
    Code:
    		null,
    		null,
    		null,
    		null,
    		null,
    		null,
    How to remove these nulls also?
    X Connections
    https://documentor.email
    https://www.x-connections.com

  • #2
    Solved it. Well kind of

    Don't know if it is the best solution, so any improvement is welcome.
    I found it is not ok to use delete on arrays.

    Delete works a little differently than you may expect with arrays, and shouldn't really be used. For one, delete doesn't affect the length of the array. For two, it leaves this undefined value in the middle of the array, which means you'll have to deal with it in code using the array.
    In summary, don't use delete on arrays.
    This does the job.
    var j=msg.results.length;
    for (i=0; i < j; i++) {
    if(msg.results[i].PMT != '1'){
    msg['results'].splice(i, 1);
    j=msg.results.length;
    i=i-1;
    }
    }

    splice does it.
    X Connections
    https://documentor.email
    https://www.x-connections.com

    Comment


    • #3
      I had a similar issue earlier this week where I needed to delete from a javascript array and shift the remaining items to fill in the gaps. I almost switched to using a java linked list instead to make it easier, but ended up finding splice and basically implemented it the same way.

      Code:
      for (var i = 0; i < msg.results.length;) {
          if (msg.results[i].PMT != '1')
              msg.results.splice(i, 1);
          else
              i++;
      }

      Comment


      • #4
        beter code

        Your code is indeed better. Nice improvement.
        X Connections
        https://documentor.email
        https://www.x-connections.com

        Comment

        Working...
        X