Using keys dynamically fetched from a JSON array file to enhance d3js functionality

I am looking to dynamically retrieve keys from an external JSON array and utilize them in d3js functions to create bar charts. Below is the JSON code provided:

[
 {   
    "Interns": 5,
    "Projects": 10,
    "Time":"Jan"
},

{
    "Interns": 16,
    "Projects": 20,
    "Time":"Feb"
}
]

My goal is to extract all keys and integrate them into d3 functions that are responsible for generating bars in a bar chart. In the example written below, d.Time is used, but I may not always know which keys have been supplied:

x.domain(data.map(function(d) { return d.Time; }));

To address this issue, I attempted to create a function that stores the keys in an array called myKeys. The data parameter in getKeys(data) pertains to the input from the d3.json() function:

var getKeys = function(arr) {
   var key, keys=[];
   for(var i=0; i< (arr.length - (arr.length - 1)); i++) {
       for(key in arr[i]) {
           keys.push(key);
       }
   }
   return keys;
}
var myKeys = getKeys(data); // Returns ["Interns","Projects","Time"]

When I use console.log myKeys[2], it correctly outputs Time. However, when attempting to use d.myKeys[2] within the domain function above, it does not produce the desired outcome. Can anyone shed some light on why this might be happening? Your assistance would be greatly appreciated!

Answer №1

When attempting to access a property of an object d by its name as a string, you should use d[mykeys[2]]. In this case, mykeys[2] contains the string "Time", so it translates to d["Time"], which is essentially equivalent to d.Time...

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

Struggling with making JSON function in XSL

Attempting to retrieve the XML content... <user-types> <section id="11" handle="user-types">User types</section> <entry id="9"> <name mode="unformatted" handle="home-owner" word-count="2" lang="en" handle-en="hom ...

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

Use jQuery to dynamically update a text field within a table row based on a selection from

My understanding of JS and jQuery is not very strong. This is the HTML Output I created using a foreach-loop: $('#ProjectOfferPosition0IsystemTypeVariantId').on('change', function () { var prices = []; prices[1] = 500.00; ...

Hide jquery scroll bar

I am currently working on a WordPress plugin with the Twenty Thirteen theme. My goal is to display a modal when a div is clicked, and at that time I want to hide the scrollbar on the body of the page. Despite trying the following code snippet, it doesn&ap ...

"Modifying Code Aesthetics in WebStorm/IDEA: A Step-by-

Here is the code style I am currently using in my JavaScript project: var obj = { a: 1 , b: 2 , c: 3 } var arr = [ 'a1' , 'a2' , 'a3' ] const w = 1 , w2 = 2 , w3 = 3 The team claims they are following npm's co ...

What is the method for handling a get request in Spring3 MVC?

Within the client side, the following JavaScript code is used: <script src="api/api.js?v=1.x&key=abjas23456asg" type="text/javascript"></script> When the browser encounters this line, it will send a GET request to the server in order to r ...

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

The inconsistency of Selenium's StaleElementReferenceException error and the variability of pageload completion codes is causing issues with clicking on elements

Big shoutout to the amazing stackoverflow community for always providing assistance. Lately, I've been grappling with the frustrating "StaleElementReferenceException" issue and haven't found a universal solution yet. Some helpful members have rec ...

show button after the page has finished loading

I have a button similar to this: <input type="submit" id="product_197_submit_button" class="wpsc_buy_button" name="Buy" value="Add To Cart"> However, I am encountering an issue where if the user clicks the button before all scripts are loaded, an e ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

Extracting data from a JSON API URL using C# in Unity

I've been working on a project where I need to parse data from a JSON Array to utilize in plotting functions that visualize orbits. Unfortunately, this is the one task left unfinished before I can complete my project. I've been trying to parse th ...

Converting a Unix timestamp of type long to a readable date format when serializing an object to JSON using System.Text.Json

There are occasions when I need to send a basic email to clients containing data stored in objects. However, the objects store date time as a long Unix Timestamp, which is not easily readable for most people and needs to be converted into a more understand ...

Developing Reactive Selections with Material-UI is made easy

After spending about 5 hours on a task that I thought would only take 15 minutes, I still can't figure out the solution. The issue is with my React App where I have two dropdowns in the Diagnosis Component for users to select Make and Model of their a ...

Do we need to use the render method in ReactJs?

I'm curious about how ReactJs uses its Render() functionality. Let's say we have some HTML code within index.html: <section id="Hello"> <h1>Hello world</h1> <p>Something something Darkside</p> </section&g ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

The form validation feature in NestJS using Class Validator appears to be malfunctioning

Hey everyone, I've been working on validating incoming form data using the class validator package and DTO. Here's my DTO: import { IsString, IsPhoneNumber, IsEnum, MinLength } from 'class-validator'; export class CreateAgentDto { @ ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

Leveraging Angular for Parsing JSON Data

I have a JSON object that I want to use in my code. The goal is to assign the values of certain properties from the JSON object to four variables in my Angular project. These variables are named as follows: authorText : string; titleText : string; duratio ...

the key of the global variable object is not displaying as being defined

Currently tackling some old legacy code that heavily relies on JQuery, and I'm stuck at a critical juncture. It seems like the process begins with initializing vm.products in newView = new DOMObj(). Then comes the data call, where a worker iterates t ...

Issues Arising When Transmitting a Multidimensional Array from Jquery to PHP - Where Am I Going Astray?

I'm struggling to send a multidimensional array [N][N] from JavaScript to PHP. Despite trying several solutions I found here, I can't seem to figure out where I'm going wrong. Below is the JQuery code I'm using to save values from an H ...