format return json with javascript

0

I have the following code

function functionCLick(name) {  
   $.getJSON('livros.json', function(data){
       $.each(data, function(i, item){
            if(item.name == name){
                $("#conteudo").html("<p>"+item.chapters+"</p>");
            }
       });
    });
 }

follows a part of json

[
    {
        "abbrev": "hob", 
        "chapters": [
            [
                "exemplo1.",
                "exemplo2.",
                "exemplo3."

            ],
            [
                "exemplo4.",
                "exemplo5.",
                "exemplo6."
            ] 
        ],
        "name": "hoobit"
    },
]

My question is the following I wanted to know if there is a way to format the output. My output in the browser is as follows, it inserts in the html all the content that is in chapters including it also shows the commas of json example line: example1., example2., example3., example4., example5., example6. it returns the commas that are at the end of each line of json's chapters . I thought of removing all the commas with the jquery but thinking, in the text there may be some comma that can not be removed. And another doubt about breaking the chapters

    
asked by anonymous 06.07.2018 / 00:20

1 answer

0

The item.chapters is returning the two arrays, soon to be separated by commas, including the values of each. What you need to do is another .each to return the subarrays and their values within each paragraph:

  

I placed a comma in exemplo1 and exemplo5 to show that the   commas within the values are not affected.

var data = [
    {
        "abbrev": "hob", 
        "chapters": [
            [
                "exemplo1,.",
                "exemplo2.",
                "exemplo3."

            ],
            [
                "exemplo4.",
                "exemplo5,.",
                "exemplo6."
            ] 
        ],
        "name": "hoobit"
    },
]
var name = "hoobit";
var chaps = ''; //  cria a variável vazia onde será armazenado o HTML
$.each(data, function(i, item){
   if(item.name == name){
      $.each(item.chapters, function(idx){
         $.each(item.chapters[idx], function(c, v){
            $("#conteudo").append("<p>"+v+"</p>");
         });
      });
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="conteudo"></div>
    
06.07.2018 / 02:14