Exploring JSON data using JavaScript map functions

I've been grappling with iterating through a JSON that contains a map within a map for hours, but have had no success...

Here is the JSON string:

 {
  "P31": {
    "wikibase-entityid": "Q16603799"
  },
  "P227": {
    "string": "1084653095"
  },
  "P1001": {
    "wikibase-entityid": "Q183"
  },
  "P1448": {
    "monolingualtext": "Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln"
  },
  "P1813": {
    "monolingualtext": "Betriebssicherheitsverordnung"
  },
  "P7677": {
    "string": "betrsichv_2015"
  },
  "P580": {
    "time": "+2002-10-03T00:00:00Z"
  },
  "P2671": {
    "string": "/g/1224z0c0"
  },
  "P9696": {
    "string": "11477"
  }
}

For a visual guide, refer to this image: https://i.sstatic.net/KbI4q.png

Please note that each property can have multiple values.

Essentially, I am looking to create a loop in which I have access to the property (e.g. PXXX), the type of the property (key in the inner map), and the value of the property (value in the inner map).

I've attempted to convert the string into a Map using methods like "new Map(JSON.parse(jsonStr))", "new Map(Object.entries(jsonStr))", and others, but without success.

Furthermore, my attempts at iterating through it with "for (var key in obj)" and "myMap.forEach((value_propertyInfo, key_propertyName) => {...}" have also been unsuccessful.

At times it feels like I'm iterating character by character, while other times it simply throws an error stating that the map is not iterable.

If anyone has any suggestions on what alternative approach I should be taking, I would greatly appreciate it!

Thank you!

Answer №1

If you want to access the properties of an object without using Map, you can simply iterate over the data object. Log the key first, then loop over the property's entries to log both the key and the value.

const data = {"P31":{"wikibase-entityid":"Q16603799"},"P227":{"string":"1084653095"},"P1001":{"wikibase-entityid":"Q183"},"P1448":{"monolingualtext":"Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln"},"P1813":{"monolingualtext":"Betriebssicherheitsverordnung"},"P7677":{"string":"betrsichv_2015"},"P580":{"time":"+2002-10-03T00:00:00Z"},"P2671":{"string":"/g/1224z0c0"},"P9696":{"string":"11477"}};

for (const key in data) {
  console.log(key);
  const entries = Object.entries(data[key]);
  for (const [key, value] of entries) {
    console.log(key, value);
  }
}

Answer №2

To iterate through the object's properties and extract propertyId, propertyName, and propertyValue for each item, you can use the following code snippet:

let data = //the object retrieved from the JSON

Object.keys(data).forEach((property) => {
    //Assuming each item has only one property and that is the desired property
    let dataType = Object.keys(data[property])[0];
    let value = data[property][dataType];
});

Answer №3

The current data structure is not very efficient. It relies on variable property names such as "PXXX" in the outer objects and the type in the inner objects. An ideal approach would be to have fixed property names with only the values varying. The best solution would involve using an array and iteration like this:

a=[
[prop, type, value],
[prop, type, value], // {"prop": prop, "type": type, "value":value} is also good
...
]
for(const [prop, type, value] of a) handleProperty(prop, type, value);

To achieve something close to this, we can manipulate the JSON string before parsing it:

s='{"P31":{"wikibase-entityid":"Q16603799"},"P227":{"string":"1084653095"},"P1001":{"wikibase-entityid":"Q183"},"P1448":{"monolingualtext":"Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln"},"P1813":{"monolingualtext":"Betriebssicherheitsverordnung"},"P7677":{"string":"betrsichv_2015"},"P580":{"time":"+2002-10-03T00:00:00Z"},"P2671":{"string":"/g/1224z0c0"},"P9696":{"string":"11477"}}'

data=JSON.parse(s.replaceAll(':{',':[').replaceAll('":"','","').replaceAll('"}','"]'))
/* We now have
data={
prop:[type, value],
prop:[type, value],
...
}*/

for(const [prop,[type, value]] of Object.entries(data)) console.log(prop,type,value)

This can be achieved using Object.entries() along with destructuring assignment.

If you prefer not to modify the JSON string, then you'll need to use

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

Designing a comprehensive window evaluator for color selection

Hey everyone, I'm excited to be joining this forum and it's my first time posting. While I have some experience in programming, particularly in HTML, I've recently encountered a new challenge. I'm interested in creating a full window c ...

Leveraging Raycaster in Three.js to identify the children of ArrowHelper, specifically line and cone elements

I have successfully implemented a Raycaster for a basic painting application. This Raycaster is utilized for a "bucket tool" feature, allowing users to click on an object and change its color. While this functionality works seamlessly with geometry objects ...

Resizable and adaptable side panel

Seeking a template for a responsive sidebar that can be dragged horizontally to resize. Bootstrap compatibility is optional (using bootstrap 4.6, but other versions are acceptable) and jQuery can be utilized. An example that meets some of my requirements: ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Is there a way to retrieve a value from localStorage and use it to automatically set the selected option in a UL-based dropdown list upon page load

I have implemented a unique UL-based dropdown list that I discovered here (specifically the third model) as the foundation for a role-based selection box for my users. To enhance user experience, I am storing their role selection in localStorage so they do ...

FormArray does not properly handle invalid input focus

Although everything functions correctly with a regular FormGroup, the issue arises when dealing with a FormArray as it fails to focus on the invalid input. Here is how my form is initialized: initForm() { this.parentForm= this.fb.group({ childFo ...

Is there a way to update the value of an element that is continuously changing through a setInterval() function when hovering the mouse over it?

I am currently a novice working on developing a pomodoro timer. At the moment, when you click the button to start the timer, it switches to displaying the remaining time once activated. One of the features I want to implement is the ability for users to h ...

In React, a singular reference cannot establish focus amidst an array of references

Scenario In this scenario, we are restricted to using only keyboard navigation without any mouse clicks. Imagine a situation where we have 10 table rows displayed on the screen. Each row contains a menu button for interaction. When the tab key is pressed ...

Fancybox fails to open when clicking on the submit form

I am having an issue with the fancybox not appearing after submitting my form. Below is the code I have for the fancybox: <div class="hidden" id="fancybox-popup-form"> (your Fancybox content goes in here) </div> <style> .hidd ...

What is the best way to display an image path and add it to the Ajax success function in a CodeIgniter application?

I am struggling to display my image path correctly using append and a variable to store the value. However, whenever I try, it results in an error. Let me provide you with the code snippet: <script type="text/javascript"> $(document).ready(funct ...

Closing the React Material UI drawer with nested list items upon clickingORClicking on nested list

Currently, I am encountering an issue with my React project that utilizes Material-UI. The problem arises when I incorporate nested list items within the drawer component. Previously, everything was functioning smoothly until the addition of these nested i ...

Remove the default selection when a different option is chosen using Bootstrap

I have implemented the Bootstrap-select plugin () for a multiple select dropdown on my website. Upon page load, there is a default option that is already selected. See image below: https://i.stack.imgur.com/SzUgy.jpg <select id="dataPicker" class=" ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

Retrieving information from Mongodb using Angularjs

Although my background is in a LAMP stack, my interest has recently been piqued by the Node.js/Angluarjs combo. I now want to incorporate Mongodb into the mix, but I'm struggling to set it up. Every tutorial I come across seems to use a different stac ...

Arrays that contain multiple dimensions

I have a php multidimensional array that is structured as follows: $fields = array( array('input', 'title', 'slug', 'keywords'), array('textarea', 'content'), array('radio&ap ...

What is the best way to achieve this particular grid layout using html and css?

I have a CSS grid of icons and I am trying to create a divider between each cell that fades in opacity towards the edges, similar to an airbrush effect. However, I want the cells themselves to remain transparent so that the background pattern is still visi ...

Loading Child Controller Instead of Parent Controller in Angular UI-Router

In my Angular application, I have set up the following nested routes: .state('mapping', { url: '/mapping', templateUrl: 'app/components/mapping/mapping.html', controller: 'MapCtrl as map', abstract: ...

Read in a CSV document within my JavaScript application

Is there a way to import a CSV file into my program in JavaScript when I know the file path? For instance, if the path to the CSV file is C:/Users/User/example.csv, I want to be able to load it into my program like this: let MY_CSV_FILE = CSV_LOAD("C:/Use ...

The google analytics tag is failing to function properly after implementing ajax on the

I am currently utilizing Google Analytics to track all events on my website. I have noticed that when the gtag scripts are directly embedded into the HTML, everything works perfectly fine (I always verify the events in Google Analytics). However, after i ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...