0

I am very new to JavaScript. I am trying to insert someObject data to my table using Javascript. But unfortunately, my code is not working. I am unclear where I am going wrong. Please find my code below. Any help will be really helpful for me.

  function myFunction(){
  var data = '{ "name":"John", "age":30, "city":"New York"}'
  var obj = JSON.parse(data);
  var toSHow = document.getElementById("datum");//my table ID is datum
var empData = "";
  for(var i=0; i<obj.length; i++)
    empData += '<tr>';
    empData += '<td>'+data.name+'</td>';
    empData += '<td>'+data.age+'</td>';
    empData += '<td>'+data.city+'</td>';
    empData += '</tr>';
  }

}
toSHow.append(empData);
</script>


3 Answers 3

1

I have adjusted your code a bit and commented on it:

function myFunction(){
    var data = '[{"name":"John", "age":30, "city":"New York"}, {"name":"Doe", "age":25, "city":"LA"}]' // Converted to array and added second element for example
    var obj = JSON.parse(data);
    var toSHow = document.getElementById("datum");//my table ID is datum

    for(var i=0; i < obj.length; i++) {
        // Reset empData every loop
        var empData = "";

        // Create new element to attach instead of adding plain text
        var newTr = document.createElement('tr');

        // Get data from object by index
        empData += '<td>'+obj[i].name+'</td>';
        empData += '<td>'+obj[i].age+'</td>';
        empData += '<td>'+obj[i].city+'</td>';

        // Set table data
        newTr.innerHTML = empData;

        // Append row every loop
        toSHow.append(newTr);

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

4 Comments

hey! not getting the result even after implementing this code. Do I need to add any more parameters to my HTML..?
I implemented it here: codepen.io/sidiadevelopment/pen/yZjBdy did you make sure to call the function?
Great Dear! As I am new to JavaScript, The mistake I was doing was not calling it outside the loop. Thanks for all your effort. It really helped me a lot.
By the way, this would be the code in (more) modern JS: codepen.io/sidiadevelopment/pen/yZjBdy (might break older IE versions though)
1

I guess instead of data.name,age & city you may have to use obj.name,obj.age & obj.city

Comments

0

The variable empData is defined in myFunction, and is undefined outside it.

1 Comment

can you please suggest me where I need to declare empData in my 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.