1

i'm currently learning about javascript. I wanted to ask about printing all array elements with looping. What kind of loop/condition i should use? can anyone give me a snippet/example how to do it? thank you.

 var newObj =  [
    {
        id : "1",
        name: "one"
    },
    {
        id : "2",
        name: "two"
    },
    {
        id : "3",
        name: "three"
    },
    {
        id : "4",
        name: "four"
    },
    {
        id : "5",
        name: "five"
    },
]

console.log(newObj);
window.onload = function ()
{ 
    var x;
    
    x = newObj[0].name;
    //x = newObj[0].id;
    document.getElementById("id").innerHTML = x;
    
};
<!DOCTYPE html>
<html>
<head>
    <script src="1.js"></script>
</head>
<body>

    <h3 align="center" id="id"></h3>

</body>
</html>

3
  • 2
    there's no JSON ... you have a javascript array called newObj Commented Oct 27, 2017 at 2:11
  • 1
    my bad, i will edit it Commented Oct 27, 2017 at 2:12
  • From the code in your question you seem to know that newObj[0] will give you the first array element, and newObj[0].name will give you that element's name. Combine that with a basic for loop using the loop counter instead of the hard-coded 0 and Bob's your uncle - not necessarily the best solution, but one that you should study till you understand it. I would be surprised if introductory JS tutorials didn't cover using a loop with an array. Commented Oct 27, 2017 at 2:50

7 Answers 7

1

JavaScript supports a for...of loop. In your case, the loop could look something like this:

for (obj of newObj)
  results += obj.name + " "

document.getElementById("id").innerHTML = results;
Sign up to request clarification or add additional context in comments.

Comments

1

To loop over each object in the array:

newObj.forEach(function (item) {
    // print the object
    console.log(item);

    // print each object property individually
    for (var key in item) {
        console.log(key, ':', item[key]);
    }
});

2 Comments

can you give an example print to html please?
What do you want to print? Just print the whole thing with someElement.innerHtml = JSON.stringify(object, null, 4); You don't need to loop over anything to print a string, you just want to format it correctly.
1

I think the example presented at w3schools, here, should be helpful to you. They have looped to create headings of different sizes.

Here is a modified code for you.

window.onload = function () { 
    var x = '';
    for (let i = 0; i < newObj.length; i++) {
        x = x + "<h2>"+ newObj[i].name + "</h2>";
    }
    document.getElementById("demo").innerHTML = x;
};

Comments

1

map() is a great function to use to iterate over arrays.

newObj.map((o)=> { 
    document.write('id:'+o.id+' '+'name:'+o.name);
});

it's great because you can chain it straight off your array like this

 var newObj =  [
    {
        id : "1",
        name: "one"
    },
    {
        id : "2",
        name: "two"
    },
    {
        id : "3",
        name: "three"
    },
    {
        id : "4",
        name: "four"
    },
    {
        id : "5",
        name: "five"
    },
].map((o)=> { 
    document.write('id:'+o.id+' '+'name:'+o.name);
});

Comments

1

If you're looking to write to your HTML document (as some of your comments imply):

 const newObj =  [
    {
        id : "1",
        name: "one"
    },
    {
        id : "2",
        name: "two"
    },
    {
        id : "3",
        name: "three"
    },
    {
        id : "4",
        name: "four"
    },
    {
        id : "5",
        name: "five"
    },
]

const element = document.getElementById("id");

newObj.forEach((obj) => {
    Object.entries(obj).forEach(([key, value]) => {
        element.innerHTML+=(`<p>${key}: ${value}</p>`); // write each key-value pair as a line of text
    });
    element.innerHTML+=('<br>'); // add another line break after each object for better readability 
});
<div id='id'></div>

Comments

1

In ES2017 (modern JavaScript):

newObj.forEach((obj) => {
    console.log(obj); // log each object in the array

    Object.entries(obj).forEach(([key, value]) => {
        console.log(`${key}: ${value}`); // log each value in each object
    });
});

Breakdown:

Comments

1

My favorite approach is this one, but only because I've gotten comfortable with it.

var newObj = [ { id : "1", name: "one" }, { id : "2", name: "two" }, { id : "3", name: "three" }, { id : "4", name: "four" }, { id : "5", name: "five" }, ]

for(var i=0; i<newObj.length; i++){
  console.log(newObj[i].id + ': ' + newObj[i].name);
}

Comments

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.