Reputation: 13207
I am trying to figure out what is the best way to store and access data in javascript.
I want to select the data associated with a "identifier" who´s value is unknown before, or add a new data set with a new random "identifier".
do i do this with an array or object?
{
"data": [
{
"key1": "identfifier1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "identfifier2",
"key2": "value2",
"key3": "value3"
}
]
}
{
"data": {
"identfifier1": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"identfifier2": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}
}
any ideas, methods, best ways to do this? one way better than the other?
Upvotes: 0
Views: 128
Reputation: 140210
If you do more reads than writes, then it's better to use the object and keep a separate array of the object keys that can be sorted when needed.
data = {
identfifier1 : { key1: value1,
key2: value2,
key3: value3
},
identfifier2 : { key1: value1,
key2: value2,
key3: value3
}
}
And when you add new key:
data.identifier3 = ...
Update the ordering:
var sorted = Object.keys( data ).sort();
To iterate in an ordered way:
for( var l = sorted.length, i = 0; i < l; ++i ) {
alert( data[sorted[i]] );
}
Or you could just sort only when absolutely needed, this way even writes will be more performant.
You could make a wrapper "class" for all this that is fast for reading and sorts only when needed.
Upvotes: 1
Reputation: 251
Use JSON (your second approach). It's meant for that purpose and there are many native functions and additional libraries to support your work. It will be easy to use a database (e.g. CouchDB or MongoDB) with it, without having to convert objects.
Upvotes: 1