I form a string

for (var i = 0; i < json_length; i++) { tmppie_traffic_source+='{"title" : '+'"'+json.data[i].name+ '","litres" : '+json.data[i].visits+'},'; } 

How to make it so that in the last iteration of the loop by the end did not put a comma?

 json.data[i].visits+'},'; 

Now I solve the problem through replace , but I think it can be otherwise

    5 answers 5

    Use the JSON.stringify function to construct a JSON string .

    Unfortunately, I can’t give you a sample code, because there is no context in your code. In addition, you are probably trying to solve the XY problem .

    • You are a plus, but, based on the task, visits need to be turned into liters, so a simple JSON.stringify not enough :) Perhaps, not all the properties of the elements of the original array should fall into the properties of the elements of the new array. - br3t
    • @ br3t, in this case, it seems to me that it is better to construct a new array using the language, and then serialize it. That is, by all means try to use the library implementation of this. It’s not even clear how satisfied the TS is with the presence of quotes in the input data - mymedia
    • 2
      @ br3t, JSON#stringify has an argument that allows you to filter what gets into the result. - user207618
    • @Other but to rename the properties in the objects in the array does not get a simple function. And thanks for the link. - br3t

    Make it easier:

     let data = ['A', 42, true]; let json = `{${data.map(e => `["type": "${typeof e}", "name": "${e}"]`).join(',')}`; console.info(json); 

       var json = { data: [ {name: "John", visits: 23}, {name: "Mary", visits: 45} ]}; var json_length = json.data.length; var items = []; for (var i = 0; i < json_length; i++) { items.push('{"title" : "'+json.data[i].name+'","litres" : '+json.data[i].visits+'}'); } tmppie_traffic_source = items.join(","); console.log(tmppie_traffic_source ); 

         var json = {}; json.data = [{name:'a', visits: 1, smth: 'z'}, {name:'b', visits: 2, smth: 'y'}]; var json_length = json.data.length; var tmppie_traffic_source = []; for (var i = 0; i < json_length; i++) { tmppie_traffic_source.push({ title: json.data[i].name, litres: json.data[i].visits }); } tmppie_traffic_source = JSON.stringify(tmppie_traffic_source); console.log(tmppie_traffic_source.replace(/[\[\]]/g, '')); 

           for (var i = 0; i < json_length; i++) { tmppie_traffic_source+='{"title" : '+'"'+json.data[i].name+ '","litres" : '+json.data[i].visits+'}'+((i+1)==json_length)?'':','; } 
          • For checking the last element, it’s probably better i===(json_length-1) - br3t
          • yes i === (json_length-1) or (i + 1) === json_length - vov4ok