A
A
Aljo2021-08-07 14:59:44
JavaScript
Aljo, 2021-08-07 14:59:44

How to split json into two arrays and output each as li element?

Hello!
On the page, ajax-loading of product data into a modal window is performed. Previously, it was loaded simply as a string, now you need to split it into elements of the ul list.

The response comes like this:

{"toys":"машинка;кукла;мяч","gifts":"конструктор;набор;мячик;набор"}


How to split the answer into two one-dimensional arrays and format each of the elements in the form:
<li>машинка</li>
<li>кукла</li>
<li>мяч</li>

and insert each of the arrays into a ul with the corresponding id (toys, gifts)?

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-08-07
@aljo222

<ul class="toys"></ul>

<ul class="gifts"></ul>

function toListElements(jsonStr) { 
  function normalize(str) {
    return str.split(';').map(function(item) {
      return '<li>' + item + '</\li>';
    }).join('');
  }
  
  const jsonObj = JSON.parse(jsonStr);
  
  document.querySelector('.toys').innerHTML = normalize(jsonObj['toys']);
  document.querySelector('.gifts').innerHTML = normalize(jsonObj['gifts']);
}

toListElements('{"toys":"машинка;кукла;мяч","gifts":"конструктор;набор;мячик;набор"}');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question