Skip to content Skip to sidebar Skip to footer

Saving Data As Object Or Array?

I have some data like 4 0.128 0.039 5 0.111 0.037 6 0.095 0.036 I need to get the second and third value by a known first value. If I have a value of 4 I want to get back two var

Solution 1:

For ease of access, I'd go with an object containing arrays:

{
    '4': [ 0.128, 0.039 ],
    '5': [ 0.111, 0.037 ],
    ... 
}

A second reason for the use of objects over arrays is ease of iteration. Imagine this:

var myData = [];
myData[4]  = [ 0.128, 0.039 ];
myData[10] = [ 42, 23 ];

for (var i = 0; i < myData.length; i++)
{
    console.log(myData[i]);
}

Would give you

nullnullnullnull
[ 0.128, 0.039 ]
nullnullnullnullnull
[ 42, 23 ]

... which is probably not what you want ;)

Solution 2:

What you would want to do is save it as a json object or just as an array as shown below:

Creating:

var obj = { "4":[0.128, 0.039], "5":[0.111, 0.037],"6":[0.095, 0.036] }

Retrieving:

obj.4 -> [0.128, 0.039] OR obj['4'] OR obj[0]
obj.5[0] -> 0.111 OR obj['5'][0] OR obj[1][0]
obj.5[1] -> 0.037 OR obj['5'][1] OR obj[1][1]

Cycling through retrieved obj:

for (var key in obj) {
    alert(obj[key]); 
}

Solution 3:

I personally use arrays if the order of the elements is of importance, otherwise I use objects (objects are not good for preserving order).

  • Arrays come with methods like push(),pop(),sort(),splice().
  • Objects are good if you have a unique key.

In the end it comes down to what is the best tool for what is that you want to accomplish.

Post a Comment for "Saving Data As Object Or Array?"