45
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....

1

3 Answers 3

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);
})

Sign up to request clarification or add additional context in comments.

2 Comments

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;
@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
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) )

1 Comment

This is a very basic question that has already been answer few times. You should mark it as duplicate
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);
}

2 Comments

I typed the answer faster than searching for the duplicate and flagging it as such.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.