A
A
Alexey2020-06-23 12:38:08
JavaScript
Alexey, 2020-06-23 12:38:08

How to mark child elements when building a tree based on an array of an object?

There is an array

const data = [
  {
    id: 1122031,
    title: "Banner",
    children: [
      {
        id: 1122032,
        title: "prod 1"
      },
      {
        id: 1122033,
        title: "prod 2"
      },
      {
        id: 1122034,
        title: "prod 3"
      },
      {
        id: 1366085,
        title: "prod 6",
        children: [
          {
            id: 1362085,
            title: "prod 16"
          }
        ]
      }
    ]
  }
];

And there is a function

function createTree(data, defaultId) {
  const ul = document.createElement("ul");

  data.map((item, index) => {
    const li = document.createElement("li");
    li.textContent = item.id;

    if (item.children) {
      li.appendChild(createTree(item.children, index));
    }

    ul.appendChild(li);
  });

  return ul;
}


How can I make it appear in the list like this?
<ul>
      <li>
        children
        <ul>
          <li>
            0_children
            <ul>
              <li>0_children_0</li>
              <li>0_children_1</li>
              <li>0_children_2</li>
              <li>
                0_children_3
                <ul>
                  <li>
                    0_children_3_children_0
                  </li>
                  <li>
                    0_children_3_children_1
                  </li>
                </ul>
              </li>
            </ul>
          </li>
          <li>
            1_children
          </li>
        </ul>
      </li>
    </ul>


It is important that the index of the previous one is added to each child element and the current index is added.

I can't figure out how to do it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-23
@Psihoshit

Let the second parameter be an array of indices, empty by default (respectively, when you call the function yourself, you don't need to pass it). At the beginning of processing a data element, put its index into an array, after processing, remove it. Well, the text - collect from the array what you need:

function createTree(data, index = []) {
  const ul = document.createElement('ul');

  data.forEach((n, i) => {
    index.push(i);

    const li = document.createElement('li');
    li.textContent = index.join('_');

    if (n.children) {
      li.appendChild(createTree(n.children, index));
    }

    ul.appendChild(li);

    index.pop();
  });

  return ul;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question