Abhishek
Abhishek

Reputation: 51

Why I cannot display all array objects using JS

const demo = document.querySelector('.demo');
const persons = [
    {name: "Abhishek", age: 20, weight: "52kg"},
    {name: "Akash", age: 21, weight: "70kg"},
    {name: "Ankit", age: 20, weight: "68kg"},
    {name: "Shubham", age: 19, weight: "60kg"},
    {name: "Harsh", age: 19, weight: "80kg"},
];

persons.forEach(function(person) {
    const data = JSON.stringify(person);
    demo.innerHTML = data;
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="./style/style.css" rel="stylesheet">
    <title>Document</title>
</head>
<body>
    <h1>Learning Javascript</h1>
    <div class="demo"></div>
    <script src="main.js"></script>
</body>
</html>

I wrote this code in order to display all objects inside my array but only the last object is visible. I used JSON.stringify() to convert my object to a string. Just explain me the reason behind this flaw.

Upvotes: 0

Views: 50

Answers (1)

Rutvik Bhatt
Rutvik Bhatt

Reputation: 486

The problem is with following line:

demo.innerHTML = data;

Replace it with following and you will see everything.

demo.innerHTML += "\n" + data;

You are using forEach loop and then using the =, replacing the previous value in the demo. You should concat values.

Upvotes: 2

Related Questions