Answer the question
In order to leave comments, you need to log in
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":"конструктор;набор;мячик;набор"}
<li>машинка</li>
<li>кукла</li>
<li>мяч</li>
Answer the question
In order to leave comments, you need to log in
<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 questionAsk a Question
731 491 924 answers to any question