An array of dictionaries that are the same except for one dictionary containing an unspecified key

A while ago, I wrote some sample code to generate Euler diagrams from an array of dictionaries. Strangely enough, it only works when the array is explicitly defined in my .js file; using input from a .json file to construct it incrementally does not yield the desired results.

Below is the snippet of code that successfully produces the expected output:

var sets = [ {sets: ['A'], size: 12}, 
             {sets: ['B'], size: 12},
             {sets: ['A','B'], size: 2}];

// create the venn diagram, place in <div> with id="matrix_venn"
var chart = venn.VennDiagram()
d3.select("#matrix_venn").datum(sets).call(chart);

However, my goal was to reconstruct this by extracting data from a json file. Here is the content of my json file named matrix_breakdown.json:

{
    "A": 12,
    "B": 12,
    "A, B": 2
}

Here is the code I used to recreate the 'sets' variable for the diagram:

// import our json file with matrix counts
import data from './matrix_breakdown.json' assert { type: 'json' };

// set an array to append with dictionaries for set names and size
var sets = [];
for (let set in data) {
    // get set names in a list
    var set_split = set.split(',');

    // get the set count (size)
    var set_size = Number(data[set]);

    // setup dictionary for appending to our sets array
    var dict = {};
    dict['sets'] = set_split;
    dict['size'] = set_size;

    // append our array with the set dictionary
    sets.push(dict);
}

// create the venn diagram, place in <div> with id="matrix_venn"
var chart = venn.VennDiagram()
d3.select("#matrix_venn").datum(sets).call(chart);

This resulted in the following error message: "Uncaught TypeError: Cannot read properties of undefined (reading 'size')"

Even after console.logging both variables, they appear identical to me. What could be causing the 'size' key to be undefined in this scenario?

Lastly, here is the HTML code that imports all necessary components:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="matrix_venn"></div>
</body>

<!-- import d3 -->
<script src="https://d3js.org/d3.v4.min.js"></script>

<!-- import venn/euler diagram module -->
<script src="./venn/venn.js"></script>

<!-- import our code for producing the plot -->
<script type="module" src="./matrix_venn.js"></script>

</html>

Answer №1

The primary distinction I notice is that in your "working" data, you have sets: ['A','B'], whereas the output provided contains sets: [ "A", " B"], with a space before B.

const data = {
    "A": 12,
    "B": 12,
    "A, B": 2
}


// Initialize an array to store dictionaries for set names and sizes
var sets = [];
for (let set in data) {
    // Obtain set names in a list
    var set_split = set.split(',');

    // Retrieve the set count (size)
    var set_size = Number(data[set]);

    // Define dictionary for adding to sets array
    var dict = {};
    dict['sets'] = set_split;
    dict['size'] = set_size;

    // Add the set dictionary to our array
    sets.push(dict);
}

console.log(sets)

You could potentially resolve this by:

const data = {
    "A": 12,
    "B": 12,
    "A, B": 2
}


// Initialize an array to store dictionaries for set names and sizes
var sets = [];
for (let set in data) {
    // Obtain set names in a list
    var set_split = set.split(',').map(e => e.trim());

    // Retrieve the set count (size)
    var set_size = Number(data[set]);

    // Define dictionary for adding to sets array
    var dict = {};
    dict['sets'] = set_split;
    dict['size'] = set_size;

    // Add the set dictionary to our array
    sets.push(dict);
}

console.log(sets)
const expected = [ {sets: ['A'], size: 12}, 
             {sets: ['B'], size: 12},
             {sets: ['A','B'], size: 2}];
console.log(JSON.stringify(expected))
console.log(JSON.stringify(sets))
console.log(JSON.stringify(expected) === JSON.stringify(sets))

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

Explanation of timespan format in .net 4.5 standard serializer

I am facing an issue with deserializing a TimeSpan property in my object using both .NET serializer and Newtonsoft.Json. In my MVC Action, the timeSpan prop is being deserialized as follows: "EndTime":{"Hours":9,"Minutes":0,"Seconds":0,"Milliseconds":0,"T ...

JavaScript/jQuery Tutorial: Accessing the src attribute of images sharing a common class名

How can I extract the src values of images with the same class and display them in an empty div? For instance: <body> <img class="class1" src="http://www.mysite.com/img/image1.jpg" width="168" height="168" alt=""> <img class="class ...

Guide on Crafting an Interactive Breadcrumbs Component

How can I implement product category breadcrumbs on the product page? These breadcrumbs will represent the parent category of the product. I am utilizing Next.js and Strapi for this project. For example, here is a screenshot showing how it should look: ...

Problem with APIGEE search function

Encountered an issue while trying to retrieve an Apigee collection using the following code snippet: var my_pc_list = new Apigee.Collection( { "client":client, "type":"pc_pedidos", qs :{ql:"limit:50"} }); Error details: {"error":"query_parse","timestamp ...

Don't forget to keep track of when the user has closed

How can I ensure that the cache retains the user's action of closing the div? Currently, when I close the div and refresh the page, it reverts back to its original state. Is there a way to make this change persistent? Experience it live: Here is the ...

Execute a program using a byte array

I possess a program that is saved within a byte array. Could it be executed in C#? ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Transforming dynamic JSON element strings into a structured class

I couldn't find a relevant question regarding my current issue, so I decided to create one. The problem I'm encountering is when converting a JSON response from our UI into an object, specifically when trying to handle the "en-US" portion of the ...

Error: Unexpected end of input detected (Likely due to a missing closing brace)

I've been struggling with this bug for the past two days, and it's driving me crazy. I have a feeling that I missed a brace somewhere in my script, but despite running various tests, I can't seem to pinpoint the glitch. Hopefully, your eyes ...

When populating data, two ID fields (_id and id) are generated as duplicates

Upon retrieving information from my database, I have noticed the presence of an additional id field alongside the standard _id field. These two fields consistently contain identical values. However, it seems that the id field appears only during population ...

What is the best way to implement a new search input for my datatable while also enabling the searchHighlight feature?

I'm attempting to implement a search bar for my datatables. I need to hide the default search engine that comes with datatables, so I added a script that I found in a forum. However, when I try to run it in my code, it doesn't work and displays a ...

Numerous jQuery pop-up windows are being generated instead of just one as intended

When I load an editing form asynchronously on my web page using jQuery.get and display it within a jQuery dialog, multiple instances of the div that I apply .dialog to are unexpectedly being appended to document.body. Here is the code snippet for loading: ...

Creating a JSON array by querying a SQL server with PHP

Currently, I am facing a challenge while following a tutorial to develop an app. My hurdle lies in understanding how to work with a JSON array... My aim is to create something similar to the following structure: { "contacts": [ { ...

Trying to draw a comparison between a text box and an individual element within

I am having some difficulty comparing user-entered text in a textbox with an element in an array. function checkUserInput() { var str = imageArray[randomNumber]; var index = str.indexOf(document.getElementById('textBox').value); ...

Conceal an element along with its space, then signal the application to show alternative content using React

Greetings everyone! I seek assistance with a React Application that I am currently developing. As a newcomer to the Javascript world, I apologize if my inquiry seems trivial. The application comprises of two main elements: a loader, implemented as a React ...

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...

Difficulty recognizing sessions in production for a self-hosted Next.js application using Clerk Dev Auth

Having trouble finding the next step in debugging as I couldn't resolve the issue on Clerk's Discord or GH Issues. It seems like it might be a Next.js problem rather than a Clerk one? I am currently running a self-hosted next.js app in a docker ...

What is the @page rule in Material-UI?

Trying to incorporate Material-UI styles with react-to-print to print components can be tricky, especially when dealing with a specific component that requires a particular page size. Here's an attempt at achieving this: const styles = (theme: Theme) ...

Encountering a type error when making an Ajax request in JavaScript/jQuery

Encountering an error while trying to extract a value within a loop using jQuery. The error message is displayed below. Uncaught TypeError: Cannot read property 'no_of_optional' of undefined Below is the code I am working with. var data = $.pa ...

When implementing Firebase Cloud Messaging with React, the token generated by firebase.messaging().getToken() will vary with every refresh

I'm working on a React web app using Gatsby and I want to integrate push notifications through FCM. My firebase-messaging-sw.js service worker is set up, and I'm trying to retrieve a token using the following method in my app: messaging .req ...