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

118
Views
How to create an array/object from an ordered list?

How can I create an array or object from an ordered list, with the number as the index/key and the list item as the corresponding value?

Example list:

<ol>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
</ol>

Should result in:

{"1" => "First list item", "2" => "Second list item", "3" => "Third list item"}

I tried using Array.from() with a few variations but that didn't work

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You could use querySelectorAll to get the <li>s and iterate over them to extract their innerText into an array:

const items = [...document.querySelectorAll('li')].map(x => x.innerText);

console.log(items);
<ol>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
</ol>

The resulting array will have item[0] === 'First list item', etc.

about 4 years ago · Santiago Trujillo Report

0

First, write a query selector to get the <ol> tag and then read its children:

let ol = document.querySelector('ol')
let lis = ol.children

Then, define an object and aggregate all the <li> texts into it:

let obj = {}
for (let i = 0; i < lis.length; i++) {
  obj[i.toString()] = lis[i].innerText
}

That should create the object you're looking for.

about 4 years ago · Santiago Trujillo Report

0

One of the way to do that:

let bob = Array.from( document.querySelector('ol').children, li => li.textContent )

console.log( bob)
<ol>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
</ol>

about 4 years ago · Santiago Trujillo 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!