Reputation: 77
I'm experiencing an issue with getting the value from a javascript array.
var color = new Array();
for (var i = 0; i < 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 from color[colour]: "#d770ce"
Real output from color[colour]: undefined.
Color has something in it, Colour is a number (key), but it seems impossible to get a value from Color..
Upvotes: 2
Views: 6508
Reputation: 6531
You might want to try changing the line
var color = new Array();
to
var color = {};
What you may be looking for not an array but, the term in javascript, an object
.
EDIT
After looking at the source and doing some debugging, the problem seems to be the asynchronous executions. You're color
variable is being populated at a later time, which explains why JSON.stringify
produces an empty object when printing which the console.log
maintains the reference to the variable.
You'll want to ensure the color
variable is populated first.
Some steps on how I debugged this, (using chrome):
undefined
sources
tab where you'll see your source codecolor
is indeed an empty objectcolor
is being populatedd3.json(
Upvotes: 3
Reputation: 2090
This code here
for (var i = 0; i < datafeatures.length - 1; i++) {
color[datafeatures[i].properties.userid] = datafeatures[i].properties.linecolor;
}
Should look more like this
for (var i = 0; i < datafeatures.length - 1; i++) {
color.push({[datafeatures[i].properties.userid]: datafeatures[i].properties.linecolor})
}
It will give you the array you're looking for, I think.
Upvotes: 0