Get value by key from array javascript -
i'm experiencing issue getting value javascript array.
var color = new array(); (var = 0; < datafeatures.length - 1; i++) { color[datafeatures[i].properties.userid] = datafeatures[i].properties.linecolor; } snapshot.foreach(function (childsnapshot) { var colour = childsnapshot.wp_user; console.log(color[colour]); console.log(json.stringify(color)); console.log(color); console.log(colour); }
console.log result:
color[colour]: undefined
json.stringify(color): []
color:
[] 26: "#9d36ee" 45: "#b1c743" 56: "#f9c53c" 61: "#d770ce" 63: "#267fa1" 64: "#85002f" 68: "#78eca8" 92: "#a4a2e7" length: 93 __proto__: array(0)
colour: 61
expected output color[colour]: "#d770ce"
real output color[colour]: undefined.
color has in it, colour number (key), seems impossible value color..
you might want try changing line
var color = new array();
to
var color = {};
what may looking not array but, term in javascript, object
.
edit
after looking @ source , doing debugging, problem seems asynchronous executions. you're color
variable being populated @ later time, explains why json.stringify
produces empty object when printing console.log
maintains reference variable.
you'll want ensure color
variable populated first.
some steps on how debugged this, (using chrome):
- open chrome dev tools (ctrl+shift+i)
- go console
- click on line number prints
undefined
- you should sent
sources
tab you'll see source code - here add breakpoint clicking on line number (407, in case)
- refresh while on dev tools window, (ctrl+r)
- the javascript execution should stop @ debugger
- in state mouse on variables on source codes see values @ point in time
- you'll find
color
indeed empty object - so trace how
color
being populated - find nested under code
d3.json(
- that's when know got asynchronous problem
Comments
Post a Comment