-1

I need to use a for loop to read the values from the arrays contained in an object in order to use these a coordinates X and Y

var murderer_record = {
  Loc_X: [
    639, 681, 712, 756, 715, 701, 753, 815, 795, 788, 781, 768, 750, 732, 714,
    695, 693, 654, 624, 594, 555,
  ],
  Loc_Y: [
    288, 286, 293, 310, 368, 425, 436, 468, 506, 497, 486, 489, 500, 506, 514,
    531, 552, 523, 500, 484, 474,
  ],
};

I've been doing:

for(i = 0; i < murderer_record.Loc_X; i++) {}

but that only gives me the values of X and I need to get both values to the input them in a function at the same time

Thanks!

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • 1
    Do you want to use the index `i` that you get from iterating `Loc_X` on your `Loc_Y` array to obtain the associated values? For example: `murderer_record.Loc_X[i]` gives the x pos, and `murderer_record.Loc_Y[i]` gives the y pos. – Nick Parsons Jul 06 '21 at 12:34
  • Just check beforehand if both arrays have the same length (you may get errors otherwise) and then you can access `murder_record.Loc_X[i]` and `murder_record.Loc_Y[i]` using the same index `i` inside the loops body. – derpirscher Jul 06 '21 at 12:36
  • 2
    You have to compare `i` to `murderer_record.Loc_X.length`, and you should declare `i` with `let`. – Pointy Jul 06 '21 at 12:36

1 Answers1

0

You could use Array.map for this purpose.

We map the Loc_X coordinates to create both x and y coordinates for each point:

var murderer_record = {
  Loc_X: [
    639, 681, 712, 756, 715, 701, 753, 815, 795, 788, 781, 768, 750, 732, 714,
    695, 693, 654, 624, 594, 555,
  ],
  Loc_Y: [
    288, 286, 293, 310, 368, 425, 436, 468, 506, 497, 486, 489, 500, 506, 514,
    531, 552, 523, 500, 484, 474,
  ],
};

const coordinates = murderer_record.Loc_X.map((x, index) => {
    const y = murderer_record.Loc_Y[index];
    return [x,y];
});

console.log("Coordinates:",coordinates)
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40