javascript - Mixing Index Array with "Associative Array" -


since need access items sometime index , sometime code. idea mix integer index string index?

note code, index, amount of items never changes after data loaded.

i'm thinking of doing this, same object pushed , set hashtable.

function datainformation(code, datavalue) {     this.code = code;     this.datavalue = datavalue; }  var datalist = [];  function filldatalist() {     addnewdata(new datainformation("c1", 111));     addnewdata(new datainformation("c2", 222));     addnewdata(new datainformation("c3", 333)); }  function addnewdata(newdata) {     datalist.push(newdata);     datalist[newdata.code] = newdata; } 

then able access object either:

datalist[0].datavalue datalist["c1"].datavalue 

before used loop find item.

function finditembycode(code) {     (var = 0; < datalist.length; i++) {         if (datalist[i].code == code) {             return datalist[i];         }     }      return null; }  finditembycode("c1").datavalue 

do ever need iterate datalist in strict order? or bag of items want random access key?

if ordered iteration not concern, use object instead of array. watch out key clashes, though.

var datalist = {};  function addnewdata(newdata) {     datalist[newdata.code] = newdata;     datalist[newdata.datavalue] = newdata; }  // that's it, no other changes necessary 

if key clashes can occur - or ordered iteration necessary, or if want make particularly clean, use array , accompanying index object.

var datalist = []; var dataindex = {     bycode: {},     byvalue: {} };  function addnewdata(newdata) {     datalist.push(newdata);     dataindex.bycode[newdata.code] = newdata;     dataindex.byvalue[newdata.datavalue] = newdata; } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -