Steps to generate a composite grouping key in D3js using two different JSON attributes

I am currently working on creating a dynamic grouped and stacked chart using D3js. I have multiple checkboxes that I utilize to group data based on various attributes. One of the grouping criteria is by two specific JSON attributes: quantity and type. Here is an example of the JSON data:

[ {
"period":201408, "quantity":10, "type":"week", "sum":55.5 }, {
"period":201408, "quantity":3, "type":"month", "sum":150 }, {
"period":201408, "quantity":12, "type":"month", "sum":150 } ]

This is my typical nest function:

var nest = d3.nest()
             .key(function(d) { return d[groupBy]; });

<input type = "checkbox" name ="groupBy" value="someValue">

In this scenario, I aim to have three groups: 10 week, 3 month, and 12 month. I am attempting to create a separate case for nesting the data but am unsure how to make the key a combination of two attributes. My current attempt looks like this:

var nest = d3.nest();
if(groupBy === "specialValue"){ // groupBy represents the selected checkbox value
    // need to create a key as a combination of quantity and type....but I'm not sure how to do it
       groupBy = key;
        nest.key(function(d) { return d[groupBy]; });   
}

If anyone can provide assistance, I would greatly appreciate it.

Answer №1

If you have an array stored in a variable called data, you can use the following code:

var nest = d3.nest()
  .key(function(d) { return d.quantity + ' ' + d.type })

var grouped = nest.map(data)

This will create a structure like this for grouped:

{
   "10 week": [ { "period":201408, "quantity":10, "type":"week", "sum":55.5 } ],
   "3 month": [ { "period":201408, "quantity":3, "type":"month", "sum":150 } ],
   "12 month": [ { "period":201408, "quantity":3, "type":"month", "sum":150 } ]
}

So if you want to access all objects with "quantity": 10 and "type": "week", you can do so by using grouped["10 week"].

Alternatively, you can also do the following:

var nest = d3.nest()
  .key(function(d) { return d.quantity })
  .key(function(d) { return d.type });

var grouped = nest.map(data)

Which will result in:

{
  "week": {
    "10": [ { "period":201408, "quantity":10, "type":"week", "sum":55.5 } ]
  },
  "month": {
    "3": [ { "period":201408, "quantity":3, "type":"month", "sum":150 } ],
    "12 month": [ { "period":201408, "quantity":12, "type":"month", "sum":150 } ]
  }
}

And you can retrieve the same result as before by accessing grouped["week"]["10"].

Answer №2

To achieve this, you will need to create a nested function as shown below. For more information, please visit: this website

var nestedFunction = d3.nest()
             .key(function(data) { return data.category})
             .key(function(data) {return data.subcategory});

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

Creating a hash map for an iteration through a jQuery collection

Using the jQuery .each function, I traverse through various div elements. By using console.log, the following output is obtained: 0.24 240, 0.1 100, 0.24 240, 0.24 240, The first number on each line represents a factor and the last number is the res ...

What is the process for enabling and disabling features in PHP?

<td>Notification for Unpicked Cases</td> <td> <input type="radio" name="notify" checked value="yes">Enable&nbsp;/&nbsp; <input type="radio" name="notify" value="no">Disable </td> If the user clicks the d ...

Accessing index.html via file:// from Vue-cli template

Whenever I execute the npm run build command using this Vue-cli template, it displays this message: Hint: The built files are designed to be served over an HTTP server. Attempting to open index.html via file:// will not function correctly. Therefore, the ...

Implementing a Fixed Position for a Single Record in Extjs 4.2 Sortable Grid

Is there a way to allow users to sort by any column in a simple grid with sorting enabled, while ensuring that a specific record is always displayed at the last position (based on its ID)? I am working with ExtJS 4.2.2. ...

Error in the Express Framework

I am currently in the process of learning about Node.js and exploring the Express framework. However, I have hit a frustrating roadblock. While following a video tutorial on implementing the EJS template engine, I encountered an error that has left me stum ...

Invalid extra parameters in the $.ajax function

I am attempting to access a web service in order to retrieve some data. I must include this URL using the GET method: http://localhost/ecosat/ws/api.php?t=vw_motorista However, when I check in Chrome Developer Tools, the link is shown as: http://localho ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

How to showcase a specific JSON array item using PHP with a NODE.JS and EXPRESS API

My custom node API running Express is designed to break down a large JSON into smaller, mobile-friendly chunks. One particular section sifts through a mass of items and only returns one, but the data is still wrapped in [..], making it difficult to work wi ...

What is the best way to eliminate properties from multiple objects that are not undefined?

When attempting to remove properties from an object, it may throw an error if the property does not have a value. What is the correct method to delete similar properties from multiple objects? Main.js if (data.details.primary.transactionHistory !== undef ...

Play Json encountered a ValidationError due to a missing path

Here is a Json string to work with: [{"cid":"1039420885783365","name":"","s":"TSLA160916C00005000","e":"OPRA","p":"219.64","cs":"chb","c":"0.00","cp":"0.00","b":"190.30","a":"194.85","oi":"2","vol":"-","strike":"5.00","expiry":"Sep 16, 2016"}, ... ] ...

Clearing input fields after entering information

Is there a way to automatically assign the value from a scanner input to a variable in an input box and clear it for the next input? HTML <ion-view hide-nav-bar="true"> <ion-content class="padding"><br> <label class="item item ...

Utilizing several bespoke directives simultaneously on a single webpage, complete with callback functionality

I have successfully developed a custom directive for a full-page date picker, with some assistance from Stack Overflow. This directive utilizes ngModel to capture the selected date and triggers a callback function that is set when the directive is inserted ...

How to Handle Tab Navigation on a Mobile Website without Javascript?

My website primarily targets mobile devices, with tabs in the top navigation. Currently, these tabs are hard coded instead of utilizing Javascript. We want to ensure our site is accessible on all mobile devices, including those without Javascript support. ...

Extract the comma-separated values from an array that are combined as one

please take a look at this dropdown In my array list displayed as ng-option, some values come as PCBUs separated by commas. For example, in the JSON response, the value of the first PCBU is "NKSMO,NNOWR". I am attempting to display these as two separate P ...

Display a toolbar underneath text that has been selected using jQuery

I am attempting to display a toolbar underneath selected text once the user has made a selection. After exploring various Stack Overflow responses, I have devised the following code. My goal is for the toolbar to activate when a user selects text not only ...

What should be done if an image is not wide enough to stretch it to match the width of the window?

When the image is not full screen, it looks fine but when it's viewed in full screen, there's a white area on the right side which is likely due to the image not being large enough. Is there a way to automatically stretch the image so that its wi ...

Removing duplicates from a multidimensional array by comparing the first element in each subarray using Javascript

I need to obtain unique values from a multidimensional array. The uniqueness should be based on the first element of each item. let arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4& ...

Showcasing JSON data in an HTML table using Angular

I'm facing an issue with displaying a JSON response in a table. Below is an excerpt from my controller.js file: var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', function($scope, $http) { $scope.choice ...

Sometimes the Ajax beforesend method may fail to function as expected

Within my application, I have a standard JSP tile that is included on all pages. In an effort to enhance security, I'm working on injecting a security token into all Ajax requests. To achieve this, I've added the following code snippet to the hea ...