Exploring deep levels of JSON data structures

I am currently dealing with nested JSON files and looking to extract specific data from them. Here is an example of the JSON file I'm working with:

My goal is to identify all objects in the file where the value for "size" is equal to 1, and then add the corresponding "canonical" array from each object to a new array. In the provided example, this would result in an array containing 9 unique "canonical" arrays. So far, my attempts at achieving this using recursion have not been successful.

function recursive(json){
    var arr = [];

    if (json.size == 1) {
        arr.push(json.canonical);
    } else {
        recursive(json.left);
    }
    return arr;
}

If anyone has suggestions or guidance on how to accomplish this task, I would greatly appreciate it. Thank you!

Answer №1

Here is the recommended solution:

let jsonData = "";
let dataList = [];

function processData(data) {
    if (data.size === 1) {
        dataList.push(data.canonical);
    }
    if (data.left) {
        processData(data.left);
    }
    if (data.right) {
        processData(data.left);
    }
}
//Start processing
processData(jsonData);
//Display the result
console.log(dataList);

Live demo:

$.get("https://examplewebsite.com/data.json", function(response) {
    let jsonData = JSON.parse(response);

    let dataList = [];

    (function retrieveData(data) {
        if (data.size === 1) {
            dataList.push(data.canonical);
        }
        if (data.left) {
            retrieveData(data.left);
        }
        if (data.right) {
            retrieveData(data.left);
        }
    })(JSON.parse(response));

    console.log(JSON.stringify(dataList));
});
<script src="https://cdn.example.com/jquery.min.js"></script>

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

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Can a C# MVC List<int> be transformed into a JavaScript array?

Can a MVC C# List be converted to a JavaScript array? var jsArray = @Model.IntList; I would really appreciate any assistance on this matter. ...

RegEx in JavaScript to identify and match the innerHTML property of all elements

I am currently in the process of developing a Chrome extension that needs to identify specific pages within a website, including the Log In / Sign In page, the Sign Up / Register page, the About page, and the Contact Us page. My approach involves obtainin ...

Converting HTML and CSS into a PDF using JavaScript

I am on the lookout for libraries that can cater to my specific needs, as I haven't found one that fits perfectly yet. My setup involves Node.js on Express.js for the backend, and html/css/js for the front-end. Browser support includes IE8 and up, chr ...

Is it possible to update the page title with JQuery or JavaScript?

Is it possible to modify the page title using a tag inside the body of the document with jQuery or JavaScript? ...

Webpack doesn't seem to be able to display custom fonts

I have a small project in progress using webpack. One of the tasks I'm facing is loading custom fonts. I followed the official tutorial here, where it explains how to handle assets in webpack configuration. My custom fonts are located within the src ...

Having difficulty modifying styles within the React Material-UI app bar component

I created a unique component and tried to implement it in AppBar, but the styles are not being overridden. I utilized the makeStyles hook which works perfectly fine outside of the AppBar, however, within the AppBar and ToolBar, I am encountering difficulti ...

What is the best way to eliminate duplicate data from a JSON file?

In the code snippet below, there is a function that queries and retrieves data from a getjson. The issue at hand is how to filter out repeated results so that they do not appear. Is there a way to prevent duplicate data from being displayed? var cuit ...

Immersive jQuery slideshow embellished with an interactive counter, captivating thumbnails, dynamic progress bar,

Hey there! I'm currently working on my very first website and I could really use some assistance in creating a slider with images. I've tried searching for a solution to my problem online, but even after attempting to fix the suggested plugin, I ...

Retrieving the value of a formControl within a formArray is made possible through a reactive form in

How can I retrieve the value of ItemName in my HTML code? When I attempt to use {{invoiceForm.controls[i].items.controls.itemName.value | json}}, it returns as undefined. <form [formGroup]="invoiceForm"> <div formArrayName="items" *ngFor="let ...

Analyzing and adding Angular JSON information

I'm struggling to understand why the compare function and insert function in my code aren't functioning correctly. I suspect that one reason for this could be that the function is not being called by the button. How can I confirm this? It seems l ...

Issue in the backend of the REST API: "This connection has encountered an error. It seems that the client has closed the connection unexpectedly."

Currently, I am in the process of working on a basic full stack project that requires a Java backend implementation for a REST API. For this task, I have decided to utilize the org.restlet.com framework/package along with Jetty as the server. During my te ...

What is the purpose of <Component render={({ state }) => {} /> in React?

Currently delving into the world of ReactJS, I decided to implement fullPageJS. It seems to be functioning properly, although there are certain syntax elements that remain a mystery to me. Take a look at the component below: function home() { return ( ...

When making a POST request to a Rails API, receiving a ParameterMissing error may indicate a

I've searched through a few related posts, but none of them address the issue I'm facing. Recently, I set up a basic products API using Rails: class API::V1::ProductsController < ApplicationController respond_to :json def index resp ...

How to use jQuery to delete specific table rows while keeping the first row safe from removal

Currently, I have a jQuery script that successfully removes table rows when a button is clicked. However, I want to prevent the button from removing the first row of the table. Is there a way to achieve this? $("#remove").click(function(event) { ...

Using Python to make a single API request that creates multiple records at once by using

Using Python 3 alongside an API to send a single JSON payload has been effective, but slow due to the need to send 200 items regularly: { "first_name":"Ellen", "address_country":"US" } Manually sending this payload creates two records, which is the d ...

I'm encountering an issue while trying to install npx create-react-app. I've attempted to use npm globally as well, but unfortunately, neither option is

While trying to install my React app using npx create-react-app my-app, I encountered the following errors: PS C:\Users\NAEEM UR REHMAN\Desktop\react_app> npx create-react-app my-app npm ERR! code ERR_INVALID_URL npm ERR! Invalid U ...

I'm receiving the error message "Fatal error: Call to a member function query() on a non-object," what could be causing this issue?

Need help with fixing an error on my private server realmeye. The error message I'm receiving is: Fatal error: Call to a member function query() on a non-object in /home/noxus/public_html/realmeye/index.php on line 112 =========================== ...

Why is the text returned by the Angular Response body missing the JSON brackets? Strange, isn't it

As a newcomer to Angular 2, I should mention that some information is internal and will be replaced with placeholders when needed. My current task involves making a simple post request and retrieving the contents of the request body. Below is my existing ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...