function nestObject()

in read_input/util.js [253:310]


function nestObject(flatObject, delimiter = ".") {
  const nestedObject = {};

  for (const flatKey in flatObject) {
    // splits by delimiter escapes delimiter in quotes
    var re = new RegExp(
      String.raw`(?:[^${delimiter}"']+|['"][^'"]*["'])+`,
      "g"
    );
    // const keys = flatKey.match(/(?:[^\."']+|['"][^'"]*["'])+/g);
    const keys = flatKey.match(re);
    let currentLevel = nestedObject;
    let lastKeyIndex = keys.length - 1;

    for (let i = 0; i < keys.length; i++) {
      // trim "" quoted key
      const key = trimQuotes(keys[i]);
      // matches [0][1][2] in key
      const arrayMatch = key.match(/^(.+?)\[(.+)\]$/);
      if (arrayMatch) {
        const arrayKey = arrayMatch[1];
        const arrayIndices = arrayMatch[2].split("][").map(Number);

        currentLevel[arrayKey] = currentLevel[arrayKey] || [];
        let currentArray = currentLevel[arrayKey];

        for (let j in arrayIndices) {
          var arrayIndex = arrayIndices[j];
          while (currentArray.length < arrayIndex) {
            currentArray.push(null);
          }
          // skip last nested array
          if (j < arrayIndices.length - 1) {
            currentArray[arrayIndex] = currentArray[arrayIndex] || [];
            currentArray = currentArray[arrayIndex];
          }
        }
        // assign data at last nested array
        if (i === lastKeyIndex) {
          currentArray[arrayIndex] = flatObject[flatKey];
        } else {
          // If NOT last key in path, ensure array element is an object
          currentArray[arrayIndex] = currentArray[arrayIndex] || {};
          currentLevel = currentArray[arrayIndex];
        }
      } else {
        // Handle object keys normally
        if (i === lastKeyIndex) {
          currentLevel[key] = flatObject[flatKey];
        } else {
          currentLevel[key] = currentLevel[key] || {};
          currentLevel = currentLevel[key];
        }
      }
    }
  }
  return nestedObject;
}