-4

I am trying to access all values in an array of objects. My data structure is like this:

var data = [
  obj{
    x: 1,
    y: 2
  },
  obj{
    x:3,
    y:9
  }
]

I would like to get values of every x at once.

I tried to use a for loop and then assign values to global variables like this:

var var startValue;
var startYValue;
var startXValue;
var endYValue;
var endXValue;
var endValue;
for (var i = 0; i < data.length; i++) {
  endYValue = data[i].endY;
  endXValue = data[i].endX;
  endValue = { x:endYValue, y:endXValue }
  startYValue = data[i].startY;
  startXValue = data[i].startX;
  startValue = { x:data[i].startY, y:data[i].startX }
  console.log(endValue.x)
    }

  console.log(endValue.x)

And I found out the first console.log(endValue.x) worked but when I console.log(endValue.x) globally, it only showed the last x value instead of all x values.

Any help would be much appreciated!!

fabrice
  • 11
  • 1

2 Answers2

0

Your data array should be just objects for each item, then we can loop through and assign each prop to another array:

var data = [{x:1, y:2}, {x:3,y:9}];
var arr = [];

// get values of every x at once.
for (var i=0; i<data.length; i++) arr.push(data[i].x);
console.log(arr); // [1, 3]
Data
  • 1,337
  • 11
  • 17
0

There exists in operator for loops:

var data = [{x:10, y: 20}, {x: 30, y: 40}];
for (var i in data) {
    var obj = data[i];

    if (!obj)
        continue;

    console.log(obj.x);
    console.log(obj.y);
}

To access first object: vas startValue = data[0];.

To access last object: vas startValue = data[data.length - 1];.

To loop througs array and find lowest/biggest x/y values:

var upperLeft = {x: data[0].x, y: data[0].y};
var bottomRight = {x: data[0].x, y: data[0].y};

for (var i in data) {
    var obj = data[i];

    if (!obj)
        continue;

    if (obj.x < upperLeft.x)
        upperLeft.x = obj.x;

    if (obj.y < upperLeft.y)
        upperLeft.y = obj.y;

    if (obj.x > bottomRight.x)
        bottomRight.x = obj.x;

    if (obj.y > bottomRight.y)
        bottomRight.y = obj.y;

}

console.log(JSON.stringify(upperLeft));
console.log(JSON.stringify(bottomRight));
ankhzet
  • 2,517
  • 1
  • 24
  • 31