-1
<p id="demo"></p>

<script>
var txt = "";
var person = [{fname:"John", lname:"Doe", age:25},
{fname:"John2", lname:"Doe2", age:35}]; 

var x;

for (x in person) {
    txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

In this code i am not able to use FOR/IN loop correctly. so help me.

dpk45
  • 107
  • 2
  • 12
  • 3
    Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) What is the end result you want? What are you getting instead? What about that do you not understand? – T.J. Crowder Dec 29 '16 at 11:34
  • 1
    Right now this is basically a duplicate of [*For-each over an array in JavaScript?*](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript). – T.J. Crowder Dec 29 '16 at 11:35
  • Its not good practice to use for-in loop on arrays in javascript. Use naive for loop only – Aravinder Dec 29 '16 at 11:37
  • What output are you hoping for @dpk45? – James Monger Dec 29 '16 at 12:25
  • – dpk45 Dec 30 '16 at 06:19

2 Answers2

0

Try this one you have to select fname,lname and age in for loop as below

 var txt = "";
    var person = [{fname:"John", lname:"Doe", age:25},
    {fname:"John2", lname:"Doe2", age:35}]; 

    var x;

    for (x in person) {
        txt += person[x].fname + " ";
        txt += person[x].lname+ " ";
        txt += person[x].age+ " ";
    }

Updated

person.forEach(function(entry) {
    txt += entry.fname + " ";
    txt += entry.lname + " ";
    txt += entry.age+ " ";
});
Curiousdev
  • 5,668
  • 3
  • 24
  • 38
  • but for/in loop works on objects property . and here you are trying to access by using dot operator. – dpk45 Dec 29 '16 at 11:49
  • Yes but **for/in** statement loops through the **properties of an object** and you are trying to loops through **object** so in that case you can do something like this or there are many other way to iterate through array of objects – Curiousdev Dec 29 '16 at 11:58
  • your code will work if you are loops through like this way **var person = {fname:"John", lname:"Doe", age:25}** – Curiousdev Dec 29 '16 at 12:00
  • can you give an example without using dot operator? – dpk45 Dec 29 '16 at 12:02
  • 1
    @dpk45: Your question remains completely unclear (there's an "edit" link you can use to make it clearer). Why would you not want to use the dot operator? Do you not know the property names in advance? – T.J. Crowder Dec 29 '16 at 12:16
0
<p id="demo"></p>

<script>
var txt = "";
var person = [{fname:"John", lname:"Doe", age:25},{fname:"John2", lname:"Doe2", age:35}]; 
var x,y;
y=person.length;
for(var i=0;i<y;i++){
for (x in person[i]) {
    txt += person[i][x] + " ";
}}
document.getElementById("demo").innerHTML = txt;
</script>

well i found the right answer thnx to all.

dpk45
  • 107
  • 2
  • 12