Home > Enterprise >  How to create an array/object from an ordered list?
How to create an array/object from an ordered list?

Time:07-21

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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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>

  • Related