Tick-Tack
Tick-Tack

Reputation: 213

How can I avoid duplicating the same object on the screen using ID?

There is an array of objects that is stored in the json file, each object has an id.

[
    {
        "time": "1500058550",
        "id": 1
    },
    {
        "time": "1500058551",
        "id": 2
    }
]

And my js loads messages from the file, say, every 5 seconds (and displays it) because new objects can be added there. But the download from the file goes in such a way that both (new and old) objects are loaded. How can I check for an id on whether the object was already loaded or not?

callback(
  [{
      "time": "1500064939",
      "id": 1
    },
    {
      "time": "1500064940",
      "id": 2
    }
  ]);

function callback(respond) {
  setTimeout(function tick() {
    var timeNow = Date.now();
    for (var i = 0; i < respond.length; i++) {
      var data = respond[i];
      var timeInMessage = data.time * 1000;
      var diff_time = (timeNow - timeInMessage);
      if (diff_time <= 36000000) {
        var newDate = new Date(timeInMessage);
        var res = [newDate.getHours(), newDate.getMinutes(), newDate.getSeconds()].map(function(x) {
          return x < 10 ? "0" + x : x;
        }).join(":");
        var rowClone = $('.mess_hide').clone().removeClass('mess_hide');
        $('#messages').append(rowClone);
        $('.time', rowClone).html(res);
      }
    }
    setTimeout(tick, 5000);
  }, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroller">
  <table id="messages">
    <tr class="mess_hide">
      <td class="time"></td>
    </tr>
  </table>
</div>

How do I implement this check? I do not know how to do this, help.

Upvotes: 0

Views: 48

Answers (1)

webdeb
webdeb

Reputation: 13211

Store the ids in an array, and check before rendering.

var loadedItemsIds = [];

for (var i = 0; i < respond.length; i++) {
  var data = respond[i];
  if (loadedItemsIds.indexOf(data.id) >= 0) continue;
  loadedItemsIds.push(data.id);

  // do you stuff with the data
  ...
}

This is much better, faster and simpler then access the DOM, and searching there..

Upvotes: 2

Related Questions