在递归函数中遇到错误?

时间:2019-07-19 07:00:39

标签: javascript

我正在使用带有嵌套对象数组的数组。根据输入行索引在数组的值中分配值,这些值将传递到数组的索引值中。我检查了以下条件:如果存在数组对象,它将转换为数组并调用递归函数,然后调用递归直到对象数组的值已满,但不知道为什么它不能正常工作。请帮助我解决这个错误

(function($) {
  var xmlOutput = document.querySelector(".xmlOutput");
  let templateStore = [];
  let preservedEntriesValue = [];
  let selectedTemplate = [];

  function generateDOMDropdown(selectedID) {
    let optionTemplate = templateStore.map(function(entry) {
      return `<option value="${
        entry.id
      }" ${entry.id === selectedID ? "selected" : ""}>${entry.name}</option>`;
    });
    $("#select").html(optionTemplate);
  }

  function processEntries(entries) {
    let output = "";
    for (const entry of entries) {
      output += entry;
    }
    return output;
  }

  function parseJSONToXML(input) {
    const domStructure = input.entriesValue.map(function(tagObj) {
      if (typeof tagObj === "string") {
        return `<${tagObj}></${tagObj}>`;
      } else if (Array.isArray(tagObj)) {
        if (tagObj.length > 1) {
          return `<${tagObj[0]}>${tagObj[1]}</${tagObj[0]}>`;
        } else if (tagObj.length == 1) {
          return `<${tagObj[0]}></${tagObj[0]}>`;
        }
      } else {
        const outerTag = Object.keys(tagObj).pop();
        const innerDOM = parseJSONToXML({ entriesValue: tagObj[outerTag] });
        return `<${outerTag}>${processEntries(innerDOM)}</${outerTag}>`;
      }
    });
    return domStructure;
  }

  function preFillSelected() {
    const root = selectedTemplate.root;
    const domStructure = parseJSONToXML(selectedTemplate);
    xmlOutput.innerText = vkbeautify.xml(
      `<?xml version="1.0" encoding="UTF-8"?><${root}>${processEntries(
        domStructure
      )}</${root}>`,
      5
    );
  }

  $.ajax({
    type: "get",
    url: window.location.origin + "/templates.json",
    success: function(data) {
      templateStore = data;
      if (data.length > 0) {
        selectedTemplate = data[0];
        generateDOMDropdown(selectedTemplate.id);
        preservedEntriesValue = selectedTemplate.entriesValue;
        preFillSelected();
        $("#select")
          .off("change")
          .on("change", function() {
            selectedTemplate = templateStore[$("#select").val()];
            preservedEntriesValue = selectedTemplate.entriesValue;
            preFillSelected();
            window.template = selectedTemplate;
          });
      }
    }
  });

  function generateValueJSON(
    template,
    lines,
    inputLen,
    templateLen,
    flatLen,
    cidx
  ) {
    cidx = cidx || 0;
    // console.log('Entry', lines, template, cidx);
    return Array.from(template.entriesValue.entries()).map(([idx, entry]) => {
      console.log("Lines", lines);
      if (idx < lines.length) {
        if (Array.isArray(entry)) {
          return [entry[0], lines[idx]];
        } else if (typeof entry === "object") {
          // debugger;

          const outerTag = Object.keys(entry).pop();
          const innerLength = entry[outerTag].length;
          if (cidx === 0) cidx = idx;
          const outerIdx = cidx + innerLength;
          // console.log((flatLen - templateLen - inputLen));
          // console.log({ flatLen, templateLen, inputLen, outerIdx, cidx, idx });
          const innerObj = generateValueJSON(
            { entriesValue: entry[outerTag] },
            lines.slice(idx, outerIdx),
            inputLen,
            templateLen,
            flatLen,
            idx
          );
          //   cidx = 0;
          entry[outerTag] = innerObj;
          return entry;
        }
        return [entry, lines[idx]];
      }
      return entry;
    });
  }

  function mapLength(template) {
    return template.entriesValue
      .map((entry) => {
        return typeof entry === "object"
          ? [Object.keys(entry), Object.values(entry)]
          : entry;
      })
      .flat(3).length;
  }

  $("#txtInput").on("keyup", function() {
    const lines = $(this)
      .val()
      .split("\n\n")
      .map((v) => v.trim().replace(/\n/g, "<br/>"));
    // console.log(preservedEntriesValue);
    selectedTemplate.entriesValue = preservedEntriesValue;
    templateLength = mapLength(selectedTemplate);
    const newEntriesValue = generateValueJSON(
      selectedTemplate,
      lines,
      lines.length,
      selectedTemplate.entriesValue.length,
      templateLength
    );
    // console.log(newEntriesValue);
    selectedTemplate.entriesValue = newEntriesValue;
    preFillSelected();
  });
})(window.jQuery, Node);





//here is the data array
[{
        "id": "1",
        "name": "Template Name 2",
        "root": "media",
        "entriesValue": [
            "mediaid",
            "category",
            "provider",
            "date",
            "caption_photo_1",
            {
                "image": [
                    "imageid",
                    "type",
                    "width",
                    "hfive"
                ]
            },
            {
                "video": [
                    "name",
                    "type",
                    "bitrate",
                    "size",
                    "width",
                    "hfive",
                    "headline",
                    "summary"
                ]
            }
        ]
    },
    {
        "id": "0",
        "name": "Template Name 1",
        "root": "article",
        "entriesValue": [
            "author",
            "headline",
            "cats",
            "subcats",
            "image",
            "video",
            "tags",
            "summary",
            "content"
        ]
    },
    {
        "id": "2",
        "name": "Template Name 3",
        "root": "article",
        "entriesValue": [
            "author",
            "headline",
            "cats",
            "subcats",
            "image",
            "video",
            "summary",
            "content",
            "keyword"
        ]
    },
    {
        "id": "3",
        "name": "Template Name 4",
        "root": "root",
        "entriesValue": [
            "description",
            "title",
            "languageId",
            "categoryIds"
        ]
    }
]


在第一次输入时,它可以正常工作,但是在第二次输入时,它将两个对象中的值都传递给

<image>
      <imageid>Correct</imageid>
      <type>bug</type>
      <width>bug</width>
      <hfive></hfive>``
 </image>
 <video>
      <name>bug</name>
      <type>bug</type>
      <bitrate></bitrate>
      <size></size>
      <width></width>
      <hfive></hfive>
      <headline></headline>
      <summary></summary>
 </video>

0 个答案:

没有答案