-2

I have an svg map with several points where I want to store the initial position of each point in an array. And each point has it's own ID, like point_1, point_2 etc.

I have attached a click handler to each of these and run a function when they are clicked. So what I want to do in this function is to check if the array already contains the information of the clicked element. If it doesn't, I want to create it.

This is what I want to do, in pseudo code

var arrPoints = [];

zoomToPoint('point_1');

function zoomToPoint(data_id) {
   // Does array already contain the data?
   if (!arrPoints.data_id) {
      // Add data to the array
      arrPoints.data_id.clientX = somevalue;
      arrPoints.data_id.clientY = somevalue;
   }
}

This would basically create an array that looks like this:

arrPoints.point_1[]
arrPoints.point_2[]

Where I can access the data in each .point_1 and .point_2. But I can't create an array based on a variable, like this:

arrPoints.data_id = [];

Because I end up with data_id as the actual name, not the variable that data_id actually is. So how is this usually accomplished? How can I identify each point to the actual array? Sorry for my lack of basics

Huangism
  • 16,278
  • 7
  • 48
  • 74
Kenny Bones
  • 5,017
  • 36
  • 111
  • 174
  • possible duplicate of [How to create object property from variable value in javascript?](http://stackoverflow.com/questions/2241875/how-to-create-object-property-from-variable-value-in-javascript) –  Aug 06 '14 at 13:22
  • Running through a JS tutorial real quick might be useful. –  Aug 06 '14 at 13:22

1 Answers1

2

Just use an object:

var arrPoints = {};

zoomToPoint('point_1');

function zoomToPoint(data_id) {
    // Does array already contain the data?
    if (!arrPoints[data_id]) {  // square brackets to use `data_id` as index
        // Add data to the array
        arrPoints[data_id] = {};
        arrPoints[data_id].clientX = somevalue;
        arrPoints[data_id].clientY = somevalue;
    }
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147