-1

I have an object called graphData:

Object data

I can access the data by graphData.data. This object is an array of 48 points of which is an array of 2 points (milliseconds,value). I want to loop through these 48 points and create an object of the same type but with the new data. I hope this makes sense.

Thanks

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
CR41G14
  • 5,464
  • 5
  • 43
  • 64

1 Answers1

2

I can access the data by graphData.data.

From the screenshot, it looks like it's graphData.data[0].data that's the 48-element array. graphData.data looks like a one-element array containing an object (perhaps a DOM element?) which has a data property, which is the 48-element array.

It sounds like you want to copy the array. If so, that's easy:

var newArray = graphData.data[0].data.slice(0);

That gives you a shallow copy of the array. Note that as it appears that the array contains arrays, both arrays will refer to the same array objects. (E.g., newArray[0] points to the same array object as graphData.data[0].data[0], and so if you modify that array, you'll see the modification regardless if which reference you use to get it.)

Or if you need to do something more complicated (perhaps copying the contained arrays as well), looping through arrays is straightforward (you have lots of options), as is creating new ones:

var data = graphData.data[0].data;
var newArray = [];
var index;
for (index = 0; index < data.length; ++index) {
    // For example, copying the contained array
    newArray[index] = data[index].slice(0);
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875