I need to list the items with set of object arrays, i could not get it.. pls help me

<script>
var emp = [ {firstname: "raj", id:111, age:30; salary:3567},
            {firstname: "uva", id:222, age:35; salary:4567},
            {firstname: "pup", id:333, age:32; salary:7865},
            {firstname: "rav", id:444, age:33; salary:7654}];

var emplist = emp.length;

var doc = "<div>";
    for(i=0; i < emplist; i++){
        doc += "<p>" + emp[i].firstname + emp[i].id + emp[i].age + emp[i].salary + "</p>";
    }
    doc += "</div>";
    document.getElementById("demo2").innerHTML = doc;
</script>

3 Answers

1
amithm7 On Best Solutions

While defining array of objects, you have put a ; after age values.

<script>
var emp = [ {firstname: "raj", id:111, age:30, salary:3567},
            {firstname: "uva", id:222, age:35, salary:4567},
            {firstname: "pup", id:333, age:32, salary:7865},
            {firstname: "rav", id:444, age:33, salary:7654}];

var doc = "<div>";
emp.forEach(function(empi){
    doc += "<p>" + empi.firstname + empi.id + empi.age + empi.salary + "</p>";
});
doc += "</div>";
document.getElementById("demo2").innerHTML = doc;
</script>
0
Maheer Ali On

You can just use Object.values() and join() because you are combining all the values. And also use Template Strings to avoid repetition of +. I think using map() is better here.

var emp = [ {firstname: "raj", id:111, age:30, salary:3567}, {firstname: "uva", id:222, age:35, salary:4567}, {firstname: "pup", id:333, age:32, salary:7865}, {firstname: "rav", id:444, age:33, salary:7654}];

document.getElementById("demo2").innerHTML = emp.map(Object.values).join('<p>');
<div id="demo2"></div>

If you still want to use forEach then use below snippet

var emp = [ {firstname: "raj", id:111, age:30, salary:3567}, {firstname: "uva", id:222, age:35, salary:4567}, {firstname: "pup", id:333, age:32, salary:7865}, {firstname: "rav", id:444, age:33, salary:7654}];

var doc = "<div>";
emp.forEach(x => doc += `<p>${Object.values(x).join('')}</p>`)
doc += "<div>"
document.getElementById("demo2").innerHTML = doc;
<div id="demo2"></div>

2
Pranav C Balan On

You can use Array#map method to iterate and generate individual p tags and Array#join method to concatenate them.

<div id=demo2></div>

<script>
  var emp = [ {firstname: "raj", id:111, age:30, salary:3567},
            {firstname: "uva", id:222, age:35, salary:4567},
            {firstname: "pup", id:333, age:32, salary:7865},
            {firstname: "rav", id:444, age:33, salary:7654}];
            
  document.getElementById("demo2").innerHTML = '<div>' +
            emp.map(empi => `<p>${empi.firstname} ${empi.id} ${empi.age} ${empi.salary}</p>`).join('') 
            + '</div>';
</script>