JavaScript: Looping through the properties and values of an Object

Currently working on a Django framework project where I am defining a Python variable as a dictionary like this:

dict = {
   ('ABC', 'XYZ'): [
      ('a', 'A'), 
      ('b', 'B'), 
      ('c', 'C'), 
      ....
   ]
}

and utilising this data in an HTML data-attribute during page rendering. The challenge arises when trying to access this data in JS, as JS only recognizes tuples as arrays. To loop through this object in JS and generate HTML code is the current objective. Attempting console.log(Object.entries(obj)) results in numerous arrays being generated.

In essence, the goal is represented by the following pseudo code:

function init(section) {

   var test1 = [...create HTML code....]

   return new Promise(function (resolve, reject) {

      $(section).append(test1)

      resolve()
}

$(document).ready(function () {
    var section = $("#PageFilter")
    var filters = $(section).data("filters")

    for (const [key, value] of Object.entries(filters)) {
     
       init(section).then(function () {
   
          for (let x = 0; x < value.length; x++) {
      
             var test2 = [...create some more HTML code...]

             $('find_test1').append(test2)
      
          }
      }
   }
})

UPDATE Below is an example of the stored data attribute within the DOM element:

<div 
   class="ms-auto py-4" 
   id="PageFilter" 
   data-filters="{('Region', 'cardinal'): [('EAST', 'EAST'), ('WEST', 'WEST')], ('State', 'state'): [('AL', 'AL'), ('AR', 'AR'), ('GA', 'GA'), ('KY', 'KY'), ('MS', 'MS'), ('NC', 'NC'), ....], ('Instatllation Type', 'installation_type'): [('BUILDING', 'Building'), ('EXTERNAL SERVICE', 'External Service'), ...]}"
></div>

Answer №1

Upon further investigation, I came to the realization that HTML's data attributes were only capable of storing text and not in the JSON format for parsing.

To access the object in JS, I took the following steps:

  1. I adjusted my python dict to the structure
    {'key': (tuple), 'value': [(tuple), (tuple)]}
    ...to ensure that JS could differentiate between the key and value pairs within the object.
  2. I confirmed that I utilized json.dumps(my_python_dict) while rendering the page to encode it in JSON format.

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

Loading a page with a Chitika ad using Jquery can cause site malfunctions

I am experiencing an issue with my header.php file on my website. I included another PHP file for my ad code, but it seems to load the ad and then redirect me to a blank page. Can someone please review my code and let me know if there is an error? Thank yo ...

Locate unique values for a specific field in MongoDB documents using Mongoose

Imagine a scenario where there is a Schema named MyDoc with a field called key. Here are the sample documents: [ { "key": 1 }, { "key": 2 }, { "key": 2 }, { "key": 3 }, { "k ...

Swiper slider - Utilizing the Blur Up Method to Load Images

I have incorporated the iDangerous swiper for a slider on my webpage. However, due to slow image loading, the slider appears like a thin line before the images are fully loaded, as depicted in this image. https://i.sstatic.net/gEzNZ.png The use of imagec ...

Attempting to wrap my head around the implementation of callback functions in THREEJS

Below is a snippet of code taken from a THREE.JS example that functions properly. I have used this code to create my own art gallery by reverse engineering it from the three.js code. However, I am puzzled by how materialPainting1 can be utilized in the cal ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Trouble with displaying an array of React elements in the render() function

While learning React by creating sample projects with Meteor, I've managed to grasp the basics but hit a wall. I'm utilizing a Twitter API to fetch the latest three tweets from the BOINGBOING Twitter page. The API is functional, and I can succes ...

The JQuery Mobile vclick event seems to only trigger a single time

Could someone help me understand why the vclick event is only firing once when trying to create a simple button rollover that changes its icon? I've tried using "click" and attaching the event directly to the button element, but still facing the same ...

transmit FormData containing two files and a text message to the controller

I have encountered an issue while trying to send a FormData object containing text fields, an image file, and a PDF file to an action in the controller. Despite my efforts, the form data is not being sent to the action. I have checked for errors through br ...

Determine the position within the DOM of a webpage and dynamically update the navigation menu classes to reflect the changes

Help! I am trying to create a navigation menu with links that direct users to specific parts of my page. I want to use JavaScript to add a class to each navigation menu item when the scroll bar reaches the corresponding section in the HTML. I think I know ...

Retrieve the value of a related object based on the user's click

Check out this sample code on JSFiddle <a href="#"></a> <a href="#"></a> <a href="#"></a> <a href="#"></a> <div></div> JavaScript: function Product(name, price){ this.name = name; this. ...

The functionality of Bootstrap scroll spy is compromised when used with the javascript implementation or the content within the <body> element

Check out this simplified version of my project on a fiddle. Even though it is set up correctly, it doesn't seem to work at all. https://jsfiddle.net/ybarpz3x/8/ I've spent the last 3 days trying to debug this issue but I just can't seem t ...

Send properties to axios hook that utilizes React suspense

I've been working on creating a hook that can fetch data and utilize React Suspense. With the guidance from the example on the page (and this article), I've developed a function (which I intend to convert into a hook) for fetching data. Example: ...

Problems arising from jQuery Mobile, NPM, and WebPack

After spending a considerable amount of time researching and experimenting, I am confident that I could piece something together to make it work. However, I would rather gain an understanding of the root cause of my issue. It is widely acknowledged that j ...

Passing a node.js variable to an ejs template through a post request

In my nodejs application, I utilize Express JS to handle post requests. Within the INDEX.JS FILE, the following code snippet is present: this.app.post('/profile', (req, res, next) => { let password = req.bo ...

Get your hands on a PDF containing server node and vue.js

I am facing an issue with creating a secure download link for a PDF file on the server. When clicking on the link, the file is not being downloaded properly. Ensuring that the PDF link remains hidden from the client but still allows for downloading direct ...

What could be causing bundle.js to remain in a pending status on my website?

Whenever I try to open a page from my project, the browser keeps showing loading forever and in the network tab, the status of bundle.js is pending. (Interestingly, if I open other routes of the project, everything works fine). If I remove all product var ...

Changing the main directory name in a Three.JS project triggers an unexpected aliasing glitch

Creating a new stackoverflow account just to ask a question is not my usual style, but I am completely baffled by this issue. For months, I have been struggling with a strange bug that causes a glitch in my three.js VR projects on Android. My usual method ...

The proxy feature in create-react-app does not function properly

When setting up my React app using create-react-app, I included the following in my package.json: After setting "proxy":"http://localhost:3001" in the package.json file to point to my API server running on port 3001, I encountered an issue where requests ...

What is the technique for defining sub paths in React-Router-Dom by excluding the parent path?

Imagine a Profile page that displays different components based on the path it receives. For example: /profile/posts will show the Posts component within Profile. /profile/comments will display the Comments component inside Profile. Typically, the Profi ...

Organizing device identification and dates in JavaScript/React

After receiving this JSON response from the backend server: { "assetStatus": "active", "auditLogs": { "20191115T123426": { "authorizedBy": "admin", "log": "Config update for E5:29:C7:E2:B7:64 (fieldsight-octo-d82d3224-4c11-4b7b-ae18-36 ...