简体   繁体   中英

Is array better than objects for storing and searching key value pairs in javascript?

I am fetching data from db and storing it in an array in key value pair, so that i can get values of respective keys as below

var test = [];
for ()            //fetching and storing from db
{
    test[key_array[i]] = "value i";
       .
       .
       .   
}


test["id_1"] = "value 1"; //to get the value of id_<number>

we can achive this though objects too. I wanted to know which is the better option to consider, if we want a fast and optimized code

Is array better than objects for storing and searching key value pairs in javascript?

No. In fact, you're not using the array as an array, you're using it as an object. You could literally change your

var test = [];

to

var test = {};
// or
var test = Object.create(null); // To avoid it having a prototype

and it would do the same thing you're seeing now:

 var test = {}; test["id_1"] = "value_1"; console.log(test["id_1"]); var test2 = Object.create(null); test2["id_2"] = "value_2"; console.log(test2["id_2"]); 

(And you should change it, since using an array only for its object features is confusing to people maintaining your code.)

[] is a property accessor that accepts the property name as a string. (We use it with standard arrays as well, using numbers, but in theory they get converted to strings before the property is looked up, because standard arrays aren't really arrays at all ¹.)

In ES2015+, of course, you'd probably use a Map , not an object:

 const test = new Map(); test.set("id_1", "value_1"); console.log(test.get("id_1")); 


¹ That's a post on my anemic little blog.

Arrays, are just a kind of object specialized for storing sequences of things. If you evaluate typeof [], it produces "object".

https://eloquentjavascript.net/04_data.html#h_cqg63Sxe3o

The idea of an array is store sequences of data with the same type or logic structure. Thus, is logic put the data come from a db into an array.

Note that you should avoid this because it can become very confusing :

 var test = []; test["id_1"] = "value_1"; test[-1] = "value_0"; console.log(test[-1],test["id_1"]); console.log(test.length,Array.isArray(test)); 

It lets you think that test is an array (and it is) but test[-1] and test["id_1"] are not part of the array (that's why Array.isArray(test) returns true , but test.length is still equal to 0. See explanation on link provided by mister TJ Crowder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM