Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Create tree from the ids of LIs in an unordered list

I'm trying to create valid JSON from the id's of li's in a nested unordered list: e.g here is an example list. Just to clarify I do NOT want to create the UL list, but the JSON from the li id's

<ul class="list">
    <li id="p1">1234</li>
    <li id="p2">1234
        <ul>
            <li id="s1">sdfg</li>
            <li id="s2">sdfg
                <ul>
                    <li id="sq1">sdfg</li>
                    <li id="sq2">sdfg</li>
                </ul>
            </li>
        </ul>
    </li>
    <li id="p6">1234</li>
    <li id="p8">1234</li>
</ul>

The JSON should read something like this:

[
  {
    "item": "p1"
  },
  {
    "item": "p2",
    "data": [
      {
        "item": "s1"
      },
      {
        "item": "s2",
        "data": [
          {
            "item": "sq1"
          },
          {
            "item": "sq2"
          }
        ]
      }
    ]
  },
  {
    "item": "p6"
  },
  {
    "item": "p8"
  }
]

I'm trying to create it like this:

let $arr = []
document.querySelectorAll("ul.list li").forEach($li => {
  if ($li.querySelector("ul:first-of-type")) {
    let $data = [];
    $li.querySelectorAll("ul:first-of-type li").forEach($li1 => {
      $data.push({ "item": $li1.id })
    })
    $arr.push({ "item": $li.id, "data": $data })
  } else {
    $arr.push({ "item": $li.id })
  }
})

But it's not creating the correct JSON - any clues / help that creates the correct JSON much appreciated thanks in advance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You'll need to recurse through the tree to build your object, then JSON.stringify. Here using a simple recursive loop, but you could also look at TreeWalker which is made for traversing the DOM.

function buildTree(parent) {
  let result = [];
  for (const child of parent.children) {
    const data = buildTree(child);
    if (child.id === '') {
      result = data;
    } else {
      result.push({ item: child.id, ...(data.length ? { data } : {}) });
    }
  }

  return result;
}

const tree = buildTree(document.querySelector('.list'));

console.log(JSON.stringify(tree, null, 2));
<ul class="list">
    <li id="p1">1234</li>
    <li id="p2">1234
        <ul>
            <li id="s1">sdfg</li>
            <li id="s2">sdfg
                <ul>
                    <li id="sq1">sdfg</li>
                    <li id="sq2">sdfg</li>
                </ul>
            </li>
        </ul>
    </li>
    <li id="p6">1234</li>
    <li id="p8">1234</li>
</ul>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!