简体   繁体   中英

Get value by key from array javascript

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..

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):

  • Open Chrome Dev Tools (Ctrl+Shift+I)
  • Go to console
  • Click on the line number that prints undefined
  • You should be sent to the sources tab where you'll see your source code
  • Here add a breakpoint by clicking on the line number (407, in this case)
  • Refresh while on the dev tools window, (Ctrl+R)
  • The javascript execution should stop at the debugger
  • In this state mouse over variables on the source codes to see their values at that point in time
  • You'll find that color is indeed an empty object
  • So trace back to how color is being populated
  • Find it nested under this code d3.json(
  • That's when you know you got an asynchronous problem

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.

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