Ragamffn
Ragamffn

Reputation: 319

Pass JSON data value key to function

I am drawing lines on a canvas using data supplied by a JSON object:

var data = { values:[
{ X: "04-28", Xt: "7:45 pm", Ys: 116, Yd: 74, Yp: 0},
{ X: "04-29", Xt: "2:00 am", Ys: 112, Yd: 73, Yp: 0},
//

Using a bit of jQuery to draw the line:

c.lineWidth = 4;
c.strokeStyle = '#f00';
c.beginPath();
c.moveTo(getXPixel(0), getYPixel(data.values[0].Ys));
for(var i = 1; i < data.values.length; i ++) {
    c.lineTo(getXPixel(i), getYPixel(data.values[i].Ys));
}
c.stroke();

To draw multiple lines (to take care of 'Yd' and 'Yp', and any other lines that may be needed later on) I'd like to move that bit into a function, which I could call using:

drawLine(4, '#f00', 'Ys');

The function I've tried:

function drawLine(width, style, d) {
    c.lineWidth = width;
    c.strokeStyle = style;
    c.beginPath();
    c.moveTo(getXPixel(0), getYPixel(data.values[0].d));
    for(var i = 1; i < data.values.length; i ++) {
        c.lineTo(getXPixel(i), getYPixel(data.values[i].d));
    }
    c.stroke();
}

Doesn't work. No error, but no line is drawn. It does work if I put the 'Ys' directly in the function. How do I pass that bit as an argument?

Upvotes: 1

Views: 2179

Answers (1)

rgthree
rgthree

Reputation: 7273

You don't want the d property of values[i], you want the property of the string value that d holds. You need to use obj[d], not obj.d like:

function drawLine(width, style, d) {
    c.lineWidth = width;
    c.strokeStyle = style;
    c.beginPath();
    c.moveTo(getXPixel(0), getYPixel(data.values[0][d]));
    for(var i = 1; i < data.values.length; i ++) {
        c.lineTo(getXPixel(i), getYPixel(data.values[i][d]));
    }
    c.stroke();
}

For instance:

var obj = { a:1, b:2, c:3 };
console.log(obj.a);    // 1
console.log(obj['a']); // 1    
var a = 'b';
console.log(obj.a);    // 1, still
console.log(obj[a]);   // 2, because the var a == 'b' as if:
console.log(obj['b']); // 2

Upvotes: 3

Related Questions