What is the best method for extracting and displaying a particular section of a JSON object using JavaScript?

I am seeking guidance on how to convert a document from JSON to an array, display the user's desired part of the array, and embed it in an HTML document for easy searching.

Here is the provided JSON data:

{
  "A": {
    "1": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "2": {
      "1\u00ba": [
        "Semestre 1"
      ]
    }
  },
  "B": [

  ],
  "c": {
    "2": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "3": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "44": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "G6": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "GP98": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "654": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "5556": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "7654": {
      "1\u00ba": [
        "Semestre 1"
      ]
    }
  }
}

Your assistance is greatly appreciated.

Answer №1

To achieve the desired format for your strings/collection of strings, you have a few options available.

JSON.Stringify can be used to convert a JavaScript object or value to a JSON string.

printDataWithStringify = (x) => {
  console.log(JSON.stringify(data[x]))
}

> {"1":{"1º":["Semestre 1"]},"2":{"1º":["Semestre 1"]}}

If you want to delve deeper into this, you may consider utilizing the following code snippet.

var printedStrings = []

checkNestedData = (x, y) => {

  if (typeof(x[y]) === 'object' && !Array.isArray(x[y][property1])) {
    printedStrings.push(y)
    for (var property1 in x[y]) {
      checkNestedData(x[y], property1)
    }
  } else {
    printedStrings.push(x[y]);
  }

}


printDataWithKeysAndValues = (x) => {
  var part = data[x]
  for (var property1 in part) {
    checkNestedData(part, property1)
  }
  console.log(printedStrings)
}

> 1,1º,Semestre 1,2,1º,Semestre 1

The above code makes use of a for...in loop to iterate over JavaScript objects. Here, part represents the object obtained when extracting information from data at key x. The variable property1 serves as the key for the current object and acts as the iterator for the loop through part.

In addition, the function checkNestedData examines whether there is another nested object within the current object. If an object (excluding those with arrays as children) is encountered, it adds the key (y) to the defined printedStrings array. The function then recursively calls itself on the current iteration of the new loop.

This recursive process continues until the last child is not an populated object.

Upon completion of looping through the entire object and storing the extracted keys and values (including nested objects), the final array containing all the keys and values for that portion ("A") of data is displayed using console.log.

Based on your formatting preferences, you can further modify the strings by using interpolation or concatenation. However, this solution effectively captures every key and value, storing them as strings in an array.

var data = {
  "A": {
    "1": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "2": {
      "1\u00ba": [
        "Semestre 1"
      ]
    }
  },
  "B": [

  ],
  "c": {
    "2": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "3": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "44": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "G6": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "GP98": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "654": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "5556": {
      "1\u00ba": [
        "Semestre 1"
      ]
    },
    "7654": {
      "1\u00ba": [
        "Semestre 1"
      ]
    }
  }
}

printDataWithStringify = (x) => {
  console.log('STRINGIFY: ' + JSON.stringify(data[x]))
}

var printedStrings = []

checkNestedData = (x, y) => {

  if (typeof(x[y]) === 'object' && !Array.isArray(x[y][property1])) {
    printedStrings.push(y)
    for (var property1 in x[y]) {
      checkNestedData(x[y], property1)
    }
  } else {
    printedStrings.push(x[y]);
  }

}


printDataWithKeysAndValues = (x) => {
  var part = data[x]
  for (var property1 in part) {
    checkNestedData(part, property1)
  }
  console.log('ALL KEYS AND VALUES: ' + printedStrings)
}


printDataWithStringify("A")
printDataWithKeysAndValues("A")

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

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

How can specific times be disabled using Laravel-9 jQuery Timepicker?

$(document).ready(function(){ $('#time').timepicker({ timeFormat: 'h:mm a', interval: 60, minTime: '9', maxTime: '4:00pm', defaultTime: '9', startTime: '9:00', dyna ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Exploring the intricacies of nested JSON in Django Templates

Currently, I am facing a challenge with printing the results of an API call that returns JSON data nested deeply. My project utilizes Python 2.7 and Django 1.11. The view.py function in my code looks like this: def nlu_analysis(request): if request.met ...

Having trouble importing images in React and passing them as a prop?

I'm attempting to import images, place them into an array, and then pass that array to a prop in a component to display different images. However, after passing the array to the component, the items accessed from the array are showing as undefined, pr ...

Golang decodes JSON using static typing rather than dynamic typing

I used to believe that json.Marshal utilized reflection to examine the passed type and then decoded it accordingly. However, I encountered an issue when I had a variable with a static type of any which actually stored a struct, and when passed to json.Unma ...

Storing and securing passwords in Node/Express using hashing and salting techniques

Utilizing the Crypto module within Node's standard library is a necessity. I have established a POST route dedicated to handling a registration form: app.post('/superadmin/add-account', function(req, res) { // Creating shorthand variable ...

Unusual perspective of JSON with ng-jsoneditor in AngularJS

Currently, I have integrated ng-jsoneditor into my AngularJS application to display and format JSON data. I found guidance on how to implement this from both here and here. Here is the HTML code snippet: <div ng-jsoneditor="onLoad" ng-model="vm. ...

Using Node.js and JWT: A guide to securely storing and using access tokens in the Authorization header

Has anyone encountered this issue before? I've searched extensively online but haven't found much information on the topic. I'm relatively new to using node and JWTs, and my goal is to generate a JWT and store it in the Authorization header ...

How can one effectively handle elements or objects that are both event listeners and event triggers?

Yesterday, I posted a similar question but found it too complex and vague after further research, so I removed it. I have now created a new demo here, which should be self-explanatory for the most part. Below are the HTML and JavaScript sections: <sel ...

How can I create a list that combines elements from an array with an integer value at the beginning?

In my coding project, there is a class named Foo which consists of a float property and a Bar object. public class Bar { //Holds various data } public class Foo { public Foo(Bar _key, float _score) { Key = _key; Score = _score; ...

What is the best way to extract user input and pass it to an AJAX request URL?

Recently, I successfully completed an AJAX request using AngularJS. You can check out the code here. Everything was working perfectly until I tried to add a dynamic variable (city) to the link like this: $http.get('http://api.wunderground.com/api/KEY ...

Is the Ajax feature not working properly when it comes to updating the page display?

I am currently working on a project to create a webpage that can display console output in real-time. Despite numerous attempts, I have not been successful so far. Below is the latest code snippet that I have tried. <!DOCTYPE HTML PUBLIC "-//W3C//DTD H ...

Updating the properties of items in an array using React

Today, I was working on React and found myself stuck due to my limited JavaScript knowledge. I am trying to update the "name" property value of any object in this array. Check out the Codesandbox demo: https://codesandbox.io/s/dank-rain-udjcxe?file=/src/ ...

What causes the maximum update depth exceeded error in React when trying to set data to the context?

When building my React project, I implemented a context to share the selected currency across components. While the context functionality is working well, I encountered a small issue regarding setting a default currency. At the start of the web applicati ...

Deciphering Complex Json Structures without the Need for Specific Keys

The contents of the json file below are municipalities in a country along with the cities they cover. However, I am having trouble parsing this information in my code. The list of municipalities is not fixed as it depends on the sender's input. I have ...

Putting together Modular Client-side JavaScript

Is there a way in Node.js to dynamically "require()" javascript files similar to PHP's require function? It would be great to use this feature in my client-side code for development purposes without actually calling a specific javascript function. Rat ...

Insert, delete, and modify rows within the table

I'm struggling with a JavaScript issue and could use some help. How can I add a new row for all columns with the same properties as the old rows, including a "remove" button for the new row? Is there a way to prevent editing cells that contain b ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...