How To Update Arrays of Javascript Objects

I’ve been doing some front-end web development and a common situation has come up again and again:

  • You’ve request a set of objects from a server (json or xml)
  • You store them in an array
  • The user does something
  • You need to request a changed set of objects and update that array

You’ve got two options here:

  1. Destroy the original array (and create all new objects)
  2. Loop through the original array to remove objects that aren’t in the new set and then add objects from the new set that aren’t in the original

Frequently option 1 isn’t really an option because destroying the original object would cause a negative experience for the end user. For instance, the screen might flash as everything they had chosen to see was temporarily destroyed and re-created.

As a result, you’ve got to take option 2. As a Javascript noob, it took me a bit of time and reading a lot of tutorials to figure out the best way to do it.

To help you avoid suffering my fate, I’ve created a quick demo of how to do it. Simply save the code below as an html file and you’ll get walked through a demo on how to do it.

    A Javascript Test