boat+hill

·舟山詩詞·淘海洗玉集 – My Poems, and etc.

Javascript: Sync JSON Data

leave a comment »

/**
 * Synchronize new data to original object and keep reference
 * Check object data type and traverse object tree to delete old key
 * as well as replace with new data:
 *
 * - if keyed data is directory (hash map) 'object', sync recursively
 * - else (including number, string, and array, etc), replace with new data
 *
 * @returns void.
 */
function syncObjectData(newData, orgData) {
  if (newData != null && orgData !== newData) {
    var sourceType = orgData.toType();
    var targetType = newData.toType();

    if (sourceType != targetType) {
      // the top level type must match

      var message = "Cannot update '" + sourceType + "' with different type " + targetType;
      throw new Error(message);
    } else if (sourceType != 'object') {
      // can only sync object type

      throw new Error("Does not support updating type of " + orgType);
    } else {
      for (var key in newData) {
        if (newData.hasOwnProperty(key)) {
          if (orgData.hasOwnProperty(key) && newData[key] != null) {
            var orgType = toType(orgData[key]);
            var newType = toType(newData[key]);

            if (newType == orgType && orgType == 'object' && orgData[key] != null) {
              syncObjectData(newData[key], orgData[key]);
            } else {
              orgData[key] = newData[key];
            }
          } else if (!orgData.hasOwnProperty(key)) {
            orgData[key] = newData[key];
          } else {
            delete orgData[key];
          }
        }
      }
      for (var key in orgData) {
        if (orgData.hasOwnProperty(key)) {
          if (!newData.hasOwnProperty(key) || newData[key] == null) {
            delete orgData[key];
          }
        }
      }
    }
  }
}

Here is the helper function to get name (string) of the exact type.

/**
 * Convert data type to string, e.g. 'undefined', 
 * or 'null', 'boolean', 'number', 'string', 'array', 'object', 'date', 'function', etc.
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
 */
function toType(variable) {
  return ({}).toString.call(variable).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

Written by Boathill

2015-12-05 at 15:00

Posted in IT, programming, study notes

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: