Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure.

**JSON**
{
    "_id" : ObjectId("5265347d144bed4968a9629c"),
    "name" : "ttt",
    "features" : {
        "t" : {
            "visual_feature" : "t",
            "type_feature" : "Numeric",
            "description_feature" : "Time"
        },
        "y" : {
            "visual_feature" : "y",
            "type_feature" : "Nominal",
            "description_feature" : "Values to be mapped to the y-axis"
        },
        "x" : {
            "visual_feature" : "x",
            "type_feature" : "Numeric",
            "description_feature" : "Values to be mapped to the x-axis"
        }
    }
}

My goal is to extract and utilize the values of the "features" attributes within the JSON object for table creation. How can I access these nested attributes (sub JSON object) in Javascript? Specifically, I need to retrieve values from "visual_feature", "type_feature", and "description_feature". UPD I have managed to find a solution.

  $.ajax({
                                url: VASERVER_API_LOC + '/visualization/' + visid + '/',
                                type: 'GET',
                                contentType: "application/json",
                                 data: tmp_object,
                                success: function(json) {   
                                    var result = [];                         
                                    var keys = Object.keys(json);
                                    keys.forEach(function (key){
                                    result.push(json[key]);
                                    });

                                    for(var i=0; i<result.length; i++){
                                    console.log(">>>  visual_feature  ==  " + result[i].visual_feature);
                                    console.log(">>> type_feature  ==   "  + result[i].type_feature);
                                    console.log(">>>  discription_feature  ==  " + result[i].description_feature);
                                    };

                                }
                            });

Thank you!!!

Answer №1

To traverse through your JSON output as an object, you can use the following loop:

for (var feature in result.features) {
  if (object.hasOwnProperty(feature)) {
    // perform actions to build a table
    console.log(feature);
  }
}

If the JSON result is not in object form, you need to use JSON.parse(result)

In order to access child properties, you may utilize another nested for loop.

Answer №2

Utilizing JSON results in the formation of regular Javascript objects.

The properties of these objects can be accessed in the same manner as any other object:

var value = obj.data.y.type;

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

The defaultLocale setting in Next.js i18n is failing to retain the default language

I am currently working on setting my default language in Next.js i18n, but I keep encountering a problem where "En" is always set as the default language, acting as a fallback. Additionally, I am receiving this error message: Error: [@formatjs/intl Erro ...

creating an interactive element that seamlessly integrates with a dynamic background image slideshow

Struggling to make this work correctly as a newbie in javascript. I need the background image to slide upon hover and stay active on its selected div when clicked. The html, css, and javascript I have currently work fine - when the user clicks on a div, a ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

What is the best way to display "SUCCESS" on the console when a launch is successful, and "ERROR" when it is unsuccessful?

Here is the question: I am delving into Node.js using the Puppeteer library, and I am looking to output "SUCCESS" in the console upon a successful execution, and "ERROR" if it fails. However, I am struggling to grasp how to achieve thi ...

How to execute a function in a child process using node.js?

In my node.js application, I am receiving a file through a web request and need to perform a time-consuming conversion process on it. To prevent this task from affecting the main thread's performance, I currently have it triggered by a setTimeout() ca ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

In the matrix game, if a user chooses two balls of the same color, those two matching color patterns will be eliminated

I am currently working on a matrix game with the following condition: When a user selects two balls of the same color, they will destroy the two patterns with the same color. I have successfully implemented horizontal and vertical selection. However, I ...

The PhantomJs browser is not able to open my application URL

Recently, my scripts in PhantomJS browser have stopped running. Whenever I try to capture screens, all I get are black screens. To troubleshoot this, I manually opened a URL in PhantomJS using the command window and ran the script below to verify if it ope ...

Ways to retrieve information from an Ajax post method call using an index similar to an array

My code doesn't seem to be working in the success function of my AJAX call. I suspect there might be an issue with how I'm specifying tr and td elements. Can someone help me identify where the problem might be? $(document).ready(function () { ...

Modifying records in mongoengine with positional operator only affects the initial element within the array

I am currently working with mongoengine and have a collection named Question. class Question(Document): id = StringField(primary_key=True) answers = EmbeddedDocumentListField(Answer) class Answer(EmbeddedDocument): id = StringField(primary_ke ...

What is the optimal approach for structuring bookmark data in couchDB?

Currently, I am diving into learning couchDB and have decided to test my skills by creating a bookmark manager as a practice project. However, I find myself stuck in the mindset of relational database management systems (RDBMS) and keep attempting to stru ...

Guide to implementing controllers in vuejs2

Hey there, I recently started using vuejs2 with a project that is based on laravel backend. In my vuejs2 project, I wrote the following code in the file routes.js export default new VueRouter({ routes: [{ path: '/test', component: ...

Tips for adjusting the position of rows within a v-data-table - moving them both up and down

Is there a way to rearrange rows up and down in the table? I've been using the checkbox feature and the CRUD data table from the documentation, but I haven't found any examples on how to implement row movement. Currently, my v-data-table setup l ...

What is the best way to show JSON array data in jQuery without using double quotes?

I have encountered an issue where I need to remove the double quotes from my json_encode output. To achieve this, I have used the following code: $json_string = json_encode($data); $json_string = str_replace('"','',$json_string); echo ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

Unable to access the URL slug within the client component in Next.js version 13

In my upcoming project with Next 13, I have a client-side component that is being rendered under the route /journal/[date] Unfortunately, I'm facing an issue trying to extract the date from the URL. I attempted to use: import { useRouter } from &apos ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Attaching an Event Listener to an array

I am struggling with a homework assignment and don't understand why I am receiving an error message saying 'undefined is not an object (evaluating 'buttons[i].style')). Any help would be appreciated. I have been attempting to loop throu ...

A Comparison: JSONArray versus JSONObject

My issue seems to be with the JSON data I'm trying to parse from this link. It appears that what I thought was a JSONArray is actually a JSONObject, or maybe I misunderstood. Previous SO questions have advised distinguishing correctly between the two ...