0

so i am building a website that uses object data that has been fetched from my database and i am trying to turn that data into valid html markup with a recursive function, this seems like something that would be possible commonly created so i am hoping i am just overlooking the complexity of this function,

this is what it looks like so far with the array loop in it, i still need to check for objects and strings


const objectData = {
  main: {
    class: "unordered list top",
    ul: [
      {
        class: "list items top",
        li: {
          class: "unordered list bottom",
          ul: [
            {
              class: "list items bottom",
              li: {
                h4: "bottom item 1",
              },
            },
            {
              class: "list items bottom",
              li: {
                h4: "bottom item 2",
              },
            },
            {
              class: "list items bottom",
              li: {
                h4: "bottom item 3",
              },
            },
          ],
        },
      },
    ],
  },
};

function iterate({ main }) {
  for (const prop in main) {
    if (Array.isArray(main[prop])) {
      return main[prop]
        .map(() => {
          `<${main}>${iterate(main[prop])}</${main}>`;
        })
        .join("");
    }
  }
}

document.addEventListener("DOMContentLoaded", () => {
  //   document.getElementById("body").innerHTML = iterate(objectData);
  console.log(iterate(objectData));
});

i have only included the array loop but im hoping someone understands where im going with this function, or maybe i am just going down the rabbit hole and not looking for an easier way do do this

1 Answer 1

2

I would say that you have chosen a bit wrong structure. Just consider the example below:

{
  class: "your class",
  li: {
    h4: "item 1",
  },
  ul: {
    h4: "item 2",
  },
  div: {
    h4: "item 3",
  },
},

As you can see, the config itself is controversial and it is not clear how the convert function should work like (especially the order of such elements inside the result DOM tree). For such cases, I would hardly recommend spending more time on developing a clear config structure.

I have already adjusted the config format and posted my result function here: https://codesandbox.io/s/blue-dew-lnwwc?file=/src/index.js

Please let me know if you have any other questions.

Sign up to request clarification or add additional context in comments.

1 Comment

yes thank you, i was trying to be silly by using object keys as a way to declare tags but it was causing to many issues, much appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.