1

I have 2 JSON arrays that are being fetched from Node API. However, I am having trouble displaying them on HTML table.

The JSON array

[ '127.0.0.1:27018', '127.0.0.1:27019', '127.0.0.1:27020' ]
[ 'SECONDARY', 'PRIMARY', 'SECONDARY' ]

AJAX call

   $.ajax({
    url: "http://localhost:8070/api/route",
    type: 'POST',
    dataType:'json',
    data: {hostname: str1, port2: str2 },
    success: function(res) {
       console.log(res);
       $.each(['result1', 'result2'], function(i, key) {
           console.log("Index",i);
           console.log("Item",key);

           $.each(res[key], function(index, value){
               console.log("key",index);   
               console.log("Value",value);
               divData='';
               divData='<tr><td>'+index+'</td><td>'+value+'</td></tr>';
               $('#restab').append(divData);   
           });
       });

       }
   });

The table comes-out this way (refer picture). I want array1 values on 1st column of the table and array2 values on the 2nd column.

enter image description here

Here are all the console logs

{result1: Array(3), result2: Array(3)}
Index result1
Item (3) ["127.0.0.1:27018", "127.0.0.1:27019", "127.0.0.1:27020"]
key 0
Value 127.0.0.1:27018
key 1
Value 127.0.0.1:27019
key 2
Value 127.0.0.1:27020
Index result2
Item (3) ["SECONDARY", "PRIMARY", "SECONDARY"]
key 0
Value SECONDARY
key 1
Value PRIMARY
key 2
Value SECONDARY

1 Answer 1

1

Check this out:

let res = {result1: [ '127.0.0.1:27018', '127.0.0.1:27019', '127.0.0.1:27020' ],
           result2: [ 'SECONDARY', 'PRIMARY', 'SECONDARY' ] },
  html = '';
  
$.each(res.result1, function(i, key) {
  html+=' <tr><td>'+key+'</td><td>'+res.result2[i]+'</td></tr>';
});
 
$('table').append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Hostname</th>
    <th>Status</th>
  </tr>
</table>

Sign up to request clarification or add additional context in comments.

2 Comments

It is giving me the same thing. All the values appear in the 2nd column.
@nomadev95 ohh ok, now I got what you really want. Updated the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.