43
var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];

How would I iterate through this. I want to print x and y value first, then 2nd and soo on....

Alex Pan
  • 4,341
  • 8
  • 34
  • 45
gaurav singh
  • 1,376
  • 1
  • 15
  • 25
  • Possible Duplicate: http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties – Rajesh Nov 04 '16 at 06:17

3 Answers3

14

Use Array#forEach method for array iteration.

var points = [{
  x: 75,
  y: 25
}, {
  x: 75 + 0.0046,
  y: 25
}];

points.forEach(function(obj) {
  console.log(obj.x, obj.y);
})
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • if i want to store the data in some var than ..var X=obj.x; var Y=obj.y; this can be done or not since m new in js; – gaurav singh Nov 04 '16 at 06:18
  • @gauravsingh this will give you only last value as you are assigning values in a loop. Please explain what you are trying to achieve and then it would be easier for us to help you. Also, next time, please refer to suggestion you get when you are asking question – Rajesh Nov 04 '16 at 06:22
4

var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];

//ES5
points.forEach(function(point){ console.log("x: " + point.x + " y: " + point.y) })


//ES6
points.forEach(point=> console.log("x: " + point.x + " y: " + point.y) )
A.T.
  • 24,694
  • 8
  • 47
  • 65
  • 1
    This is a very basic question that has already been answer few times. You should mark it as duplicate – Rajesh Nov 04 '16 at 06:18
2

You can use for..of loop.

var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];
for (let point of points) {
    console.log(point.x, point.y);
}
Rax Weber
  • 3,730
  • 19
  • 30
  • 1
    I typed the answer faster than searching for the duplicate and flagging it as such. – Rax Weber Nov 04 '16 at 06:21
  • I must say you have some typing speed, but its better to keep **our portal** clean. Also remember, Old posts have more answers covering more options , so person searching for it will help him learn more if you mark as duplicate – Rajesh Nov 04 '16 at 06:32