Home > Blockchain >  Is there a way to convert a list of li's in a ul into an array?
Is there a way to convert a list of li's in a ul into an array?

Time:11-05

I am fetching some data and it comes back like this:

> denialReasonContent: {   denialReason: "<ul>\n <li>denial reason
> 1</li>\n <li>denial reason 2</li>\n</ul>" };

I'm trying to take this data of a ul element full of li's and covert to an array that would look like this

var denialReasons = [{denialReason: denial reason 1}, {denialReason: denial reason 2}];

What's the best approach to parse this data and convert to a new array?

CodePudding user response:

If you are sure to get valid html string as a response this code can help

let denialReasonContent =  { denialReason: `<ul>\n <li>denial reason 1</li>\n <li>denial reason 2</li>\n</ul>` };


 let div = document.createElement('div');

 div.innerHTML = denialReasonContent.denialReason


 let list = div.getElementsByTagName("li")


 let data = [];


for(let i=0; i<list.length;i  ) {
  data.push({denialReason:list[i].innerText})
}

console.log(data)

// [{denialReason: denial reason 1}, {denialReason: denial reason 2}];
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related