Modify the JSON structure of a deeply nested object

I am attempting to convert a deeply nested JSON object from one structure to another so that it can be properly used with the jQuery Nestable library.

Here is the original format I am working with:


  {
      "scanned": {
          "a3": {
              "value": 906
          },
          "value": 23667
      },
      "total": {
          "printed": {
              "black": {
                  "value": 44
              },
              "color": {
                  "value": 57
              },
              "value": 101
          },
          "value": 101
      }
  }

The desired JSON format for compatibility with the library is as follows:

[
    {
        "id": "scanned: 23667",
        "children": [
            {
                "id": "a3: 906"
            }
        ]
    }, 
    {
        "id": "total: 101",
        "children": [
            {
                "id": "printed: 101",
                "children": [
                    {
                        "id": "black: 44"
                    }, 
                    {
                        "id": "color: 57"
                    }
                ]
            }
        ]
    }
]

I have attempted to traverse this tree with a recursive function but have not yet achieved the desired result:


Object.keys(o).forEach(function (k) {
   if (o[k] !== null && typeof o[k] === 'object') {
       if(parent) {
           console.log(parent);
           if(!o.children) {
               o.children = [];
           }
           o.children.push({id: k + ": " + o[k].value})
       } else {
           o.id = k + ": " + o[k].value
       }

       _this.iter(o[k], k);
       return;
   }
});

If anyone could provide me with a solution or working example, I would greatly appreciate it.

Answer №1

This particular code snippet demonstrates a function that transforms a nested object into a specific format. It loops through the keys of the provided input object and constructs a new object based on certain conditions. Any key-value pair in the original object with additional depth is recursively processed to build a tree-like structure in the final result array. The end result is an array of objects, where each object represents a different level of nesting from the initial input object.

Answer №2

Give this a try

let data = {"total":{"printed":{"black":{"value":44},"color":{"value":57},"value":101}}};

function processObject({value, ...rest}, result=[]) {
  Object.entries(rest).forEach(([key, val], index) => {
    if(Array.isArray(result)) {
      result[index] = {"id" : `${key}: ${val.value}`};
      processObject(val, result[index]);
    } else {
      result.children = result.children || [];
      result.children[index] = {"id" : `${key}: ${val.value}`};
      processObject(val, result.children[index]);

    }
  });
  return result;
}

console.log(processObject(data))

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

Accessing a JSON array from PHP script with the help of jQuery

Recently, I delved into the world of jQuery and PHP by attempting to pass variables from Javascript to a PHP script using $.ajax. Despite my lack of expertise in this area, I managed to write some code that kind of worked. However, today I encountered a n ...

Reduce the file size of CSS and JS files for Magento

We are facing an issue with minifying CSS and Javascript for our Magento website. Currently, the size of our website is 1.1 MB and we aim to reduce it to 1 MB or even lower if possible. I tried using the "CSS Settings" and "Javascript Settings" functions ...

How can we ensure that the load more button disappears at the appropriate moment in this Vue 3 application?

I have been developing a news application with Vue 3 and the News API. I am currently implementing a feature for loading more articles on the page. Initially, there are 24 articles displayed, and if there are more articles available than the current numbe ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

Dealing with the validation of two forms on a single webpage: Strategies and Solutions

In a popup, there are two forms that alternate display - one for editing (loaded via ajax) and one for creation. Using jQuery validation, I aim to show hints for both editing and field submission. The validation includes ensuring time spans do not overla ...

Tips for validating JSON strings in PHP similar to the JSON_VALID function in MySQL

Is there a way to ensure that a JSON string is valid before inserting it into a MySQL database to avoid any JSON_VALID constraint violations? I've tried using json_decode with the following code: json_decode($string, true, 512, JSON_THROW_ON_ERROR); ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Find the location in a node.js script where a promise was rejected

Recently, I encountered a code snippet from an npm package that has been causing me some trouble. The issue is that I'm having difficulty in pinpointing where the rejected promise is being created or rejected within node.js. const someHiddenEvil = fu ...

What steps should I follow to create a Lunr search functionality for Markdown MD files?

Currently, I am in search of a suitable lunr search implementation for my MD (Markdown) documents spread throughout my React/NextJS website. Our website contains a plethora of Markdown docs within both blog and regular "docs" sections, necessitating a robu ...

The Angular Google Maps Module fails to initialize

After updating angular-google-maps to version 2.0.1 via bower and adding the required dependencies (bluebird, jquery, loadash), I noticed that my app works fine when I comment out google-maps. This suggests that the issue lies with angular-google-maps. He ...

Issue with Material UI tabs: TypeError - Unable to access property 'charAt' as it is undefined

Currently, I am attempting to implement Material UI tabs in my project. Here is the component in question: const ItemssOverview = ({ details }) => { if (details && details.items) { return ( <div> &l ...

What kind of error should be expected in a Next.js API route handler?

Recently, I encountered an issue with my API route handler: import { NextRequest, NextResponse } from "next/server"; import dbConnect from "@/lib/dbConnect"; import User from "@/models/User"; interface ErrorMessage { mess ...

How to utilize a Multidimensional JSON Array in a jQuery Function

I'm struggling with passing a PHP array to a jQuery function and accessing values from a multidimensional JSON array. When I try to retrieve the value of 'lat' using the code below, I receive an error stating Cannot read property 'lat&a ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

Reducing the slide margins in impress.js?

When using Impress.js, I noticed that the default slides have a large left margin (or padding - it's hard to determine with Firefox's Inspector). I have a slide with a wide <pre> block that would fit if it were aligned to the left, but it d ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Error encountered while attempting to serialize React Fragment: Symbol value cannot be converted to a string

Encountering an issue while attempting to render a React.Fragment: Error Message: Cannot convert a Symbol value to a string Snippet of the code being passed to a component: render{ const block = { type : 'menu', className: &ap ...

SquirrelFish appears to be lacking "bind()", so how can one attach a JS callback to "this" in its absence?

Does anyone know a way to attach a JS callback to "this" without using "bind()"? Based on Samsung specifications: In 2013 with V8: everything functions as expected (refer to linked screenshot, too large to include here) In 2012 with SquirrelFish: encoun ...

Access the Windows directory through a custom HTML link

Currently, I am in the process of creating a personalized "website" that contains a collection of links leading to specific items on my computer. When I click on a link, the folder opens within the browser. Is there a way for these links to open Windows Ex ...