Send function the key of the JSON data value

Currently, I am utilizing data from a JSON object to draw lines on a canvas:

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},
//

The lines are drawn using jQuery with the following code:

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();

In order to draw multiple lines (including 'Yd', 'Yp', and potentially more lines in the future), I intend to create a function that can be called like this:

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

I attempted to create the function as follows:

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();
}

Unfortunately, this approach did not yield the desired results. While there were no errors, no lines were drawn. However, when I hardcoded 'Ys' into the function, it worked fine. How can I successfully pass this snippet of data as an argument?

Answer №1

To access the property of the string value within the d variable, you should use obj[d] instead of obj.d. Here's an example function that demonstrates this concept:

function displayValue(width, style, d) {
    canvas.lineWidth = width;
    canvas.strokeStyle = style;
    canvas.beginPath();
    canvas.moveTo(getXPosition(0), getYPosition(data.values[0][d]));
    for(var i = 1; i < data.values.length; i ++) {
        canvas.lineTo(getXPosition(i), getYPosition(data.values[i][d]));
    }
    canvas.stroke();
}

And here is a simple scenario to illustrate further:

var obj = { x:5, y:10, z:15 };
console.log(obj.x);         // 5
console.log(obj['x']);      // 5    
var prop = 'y';
console.log(obj.prop);      // undefined
console.log(obj[prop]);     // 10, since prop == 'y', equivalent to:
console.log(obj['y']);      // 10

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting databases with Spring, MongoCursor, and Jackson's JsonNode

I am facing a challenge with parsing a String retrieved from MongoCursor to work with JsonNode. My goal is to align the Json data from MongoCursor with my Spring SQL POJO for insertion into my SQL database. This essentially involves database conversion, wi ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Why does my value always revert to 0 whenever I switch screens while utilizing async storage?

Utilizing a stack Navigator, my primary screen is tracker.js, and the secondary one is macros.js. In macros.js, I have the ability to manually input nutritional macros (calories, Fats, Carbs, Protein) and add them to my UsedDailyCalories. However, when I ...

Obtain the value of a URL parameter on a webpage without needing to refresh the

I have a list of records on a webpage, each with a unique URL pointing to another page with a parameter in the URL. When any of these records are clicked, I want to display the value of the URL parameter in an alert without reloading the page. <script& ...

Is there a way to delete specific information from a JSON response?

Received the service response in the following format: Temp([ { XXX: "2", YYY: "3", ZZZ: "4" }, { XXX: "5", YYY: "6", ZZZ: "7" }, { XXX: "1", YYY: "2", ZZZ: "3" } ]); I need to manipulate this response in J ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Making a column in a Vue data grid return as a clickable button

My goal is to utilize vue.js grid to display multiple columns with calculated text values, along with a clickable column at the end that triggers a dynamic action based on a parameter (such as calling an API in Laravel). However, when I include the last c ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...

Is the MUI Drawer Open 20% of the Time?

One issue I'm facing is with my MUI drawer - it's supposed to close after a menu item is clicked, but sometimes, about 1 out of 5 times, it remains open. I have based my current code on a helpful post on Stack Overflow. Take a look at the code s ...

Tips on leveraging LocalStorage to update state in ReactJS

In my code, an array fetches API data each time componentDidMount() is called. Within this array, each element contains an object with a default boolean value of true. An onClick function toggles the boolean value of a specific element to false when clicke ...

Browserify - combine external modules into a single bundle

I am a complete beginner in the world of browserify. I recently discovered this interesting module called peer-file, which allows for file transfer between two browsers. After reading the Usage section in its readme, I realized I needed to include the scri ...

experiencing difficulty with properly passing an array in a quicksort algorithm

My program compiles and runs without syntax errors, but it fails to sort the array. The issue seems to be related to how I am passing the array in a function. #include<stdio.h> #include<string.h> int partition (int *,int,int); void quicksort ( ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Why isn't my script responding to mouse events like mouseenter, mouseover, or any other mouse event?

const element = document.getElementById("box"); element.addEventListener("mouseenter", handleMouse); function handleMouse(event) { console.log("Event type: " + event.type); } ...

The functionality of a Google chart is determined by the value of the AngularJS $scope

I recently started working with AngularJS and Google charts. I've successfully created a Google chart using data from AngularJS. It's functioning properly, but now I want to make the chart dynamic based on my Angular Scope value. I have a filter ...

React JS - State values are not persisting and rendering properly upon clicking

Recently, I followed a step-by-step tutorial on creating a todo list using functional components. However, I encountered an issue when attempting to delete or mark items as complete in the list. In both the deleteHandler and completeHandler functions, I tr ...

Working with jQuery, parsing JSON data, and making API calls to

Using the jQuery AJAX function to retrieve data from the Flickr API and get the URL for the original image size. $.ajax({ url: "http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&api_key=708f179518b2093d23f0aef284b5 ...

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

Utilize Jquery to hide radio buttons, while allowing users to click on an image to display a larger version

My current HTML structure is restricted to SAAS, so I only have control over jQuery implementation. https://i.stack.imgur.com/OHB9K.jpg I am attempting to achieve a similar layout as shown in the image below. The main issue lies in how to (1) conceal ...