0

I am trying to solve two problem from the code below.

var employees = [
    {
    firstName: "John",
    lastName :"Doe",
      qualification: {Diploma: 'IT Software' , Degree: 'Software Engineering'}
    }, 
    {
    firstName:"Anna",
    lastName:"Smith",
      qualification: {Diploma: 'Business Accountant' , Degree: 'Business Administration'}
    }
];

for(var i in employees)
  {
    console.log(employees[i]);

  }

The output from the code above is as follow.

[object Object] {
  firstName: "John",
  lastName: "Doe",
  qualification: [object Object] {
    Degree: "Software Engineering",
    Diploma: "IT Software"
  }
}
[object Object] {
  firstName: "Anna",
  lastName: "Smith",
  qualification: [object Object] {
    Degree: "Business Administration",
    Diploma: "Business Accountant"
  }
}

I am looking to index the output that is instead of [object object] it should display [index: 1] and [index : 2] for the respective object.

Your help would be appreciated. Thanks

Faraz_pk
  • 53
  • 5
  • That's not JSON. That's a JavaScript array initializer containing JavaScript object initializers. If you're in JavaScript source code, you're not dealing with JSON (unless it's in a string). – T.J. Crowder Jul 16 '15 at 10:35

2 Answers2

0

Don't use for-in (without safeguards) to loop through arrays (details and alternatives listed in this answer), that's not what it's for.

If you want both the object and its index in the array, your best bet is is forEach:

employees.forEach(function(employee, i) {
    console.log("[index: " + (i + 1) + "]");
    // And if you need the actual employee object,
    // it's `employee`
});

Note the i + 1: Indexes in JavaScript (and programming in general) usually start with 0, not 1, so to get your desired output, we add one to the index.

Alternately, a boring old for loop:

for(var i = 0; i < employees.length; ++i)
{
    console.log("[index: " + (i + 1) + "]");
    // And if you need the actual employee object, as
    // with your code, it's `employees[i]`
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

when you are looping the array in the for bucle you get the index with the variable i

for(var i in employees)
    console.log("index:"+ i);
jsertx
  • 636
  • 7
  • 17