Pre-release
AdventureJS Docs Downloads
Score: 0 Moves: 0
// replaceStringsWithObjects.js
/*global adventurejs A*/

/**
 * Replace strings in destination object with objects from source object as needed.
 * @method adventurejs#replaceStringsWithObjects
 * @memberOf adventurejs
 * @param {Object} source
 * @param {Object} destination
 */
adventurejs.replaceStringsWithObjects =
  function Adventurejs_replaceStringsWithObjects(source, destination) {
    function recurse(sourceObj, destObj) {
      for (let key in destObj) {
        if (
          typeof destObj[key] === "string" &&
          sourceObj[key] &&
          typeof sourceObj[key] === "object"
        ) {
          // Replace the string with the object from the source
          destObj[key] = sourceObj[key];
        } else if (
          typeof destObj[key] === "object" &&
          !Array.isArray(destObj[key])
        ) {
          // Recurse into nested objects
          recurse(sourceObj[key] || {}, destObj[key]);
        }
      }
    }

    recurse(source, destination);
    return destination;
  };