0
<html>
<body>
<p id="demo"></p>

<script>

var data = [
  {'name': 'person1','location': 'NY'},
  {'name': 'person2','location': 'NY'},
  {'name': 'person3','location': 'CA'}
];

var text="";
for (var i=0; i<=2; i++) {
    text+='<div>'+data[i]+'</div>';
}


data.forEach(info => {
    document.getElementById('demo').innerHTML = text;
});
</script>
</body>
</html>

Right now it's printing [object Object]. How can I show the content of the object? Is my approach of using forEach method wrong?

Jasdeep Singh
  • 7,901
  • 1
  • 11
  • 28
  • `text+='
    '+data[i]+'
    ';` This will not give you the attributes value, you have to specify the attribute you want to access like `text+='
    '+data[i].name+'
    ';` or use `.location`
    – ROOT Mar 15 '20 at 19:17

1 Answers1

0

Use the object properties instead of direct object

for (var i=0; i<=2; i++) {
    text+='<div>'+data[i].name + ' ' + data[i].location+'</div>';
}
Jasdeep Singh
  • 7,901
  • 1
  • 11
  • 28