Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node:

{
  "video": {
    "width": 1920,
    "height": 1080,
    "video_codec": "H264",
    "CBR": "4337025",
    "frame_rate": {
      "numerator": 25,
      "denominator": 1
    },
    "specified": {
      "numerator": 1,
      "denominator": 1
    },
    "gop": {
      "length": 50,
      "reference_frames": 3,
      "sub_gop": "StaticType"
    },
    "codec_details": {
      "profile": "Main",
      "level": "Level4",
      "entropy_encoding": "CABAC",
      "video_output": "AVC1"
    }
  }
}

Desired tree node structure:

export class TrackDetailsNode {
  key: string;
  value: string;
  children?: TrackDetailsNode[];
}

Example of the expected output:

{
  "key": "video",
  "children": [
    {
      "key": "width",
      "value": "1920"
    },
    {
      "key": "frameRate",
      "children": [
        {
          "key": "numerator",
          "value": "60"
        },
        {
          "key": "denominator",
          "value": "1"
        }
      ]
    }
  ]
}

Looking for a recursive approach to efficiently parse and build the tree structure from the JSON provided.

Answer №1

const videoInfo = {
  "video": {
    "width": 1920,
    "height": 1080,
    "video_codec": "H264",
    "CBR": "4337025",
    "frame_rate": {
      "numerator": 25,
      "denominator": 1
    },
    "specified": {
      "numerator": 1,
      "denominator": 1
    },
    "gop": {
      "length": 50,
      "reference_frames": 3,
      "sub_gop": "StaticType"
    },
    "codec_details": {
      "profile": "Main",
      "level": "Level4",
      "entropy_encoding": "CABAC",
      "video_output": "AVC1"
    }
  }
};

function generateNestedStructure(data, output, children) {
  Object.keys(data).forEach((key) => {
     let value = data[key];
     if (children) {
       if (typeof value === 'object') {
          const child = [];
          children.push({
             'key': key,
             children: child
          });
          generateNestedStructure(value, undefined, child)
       } else {
          children.push({
             'key': key,
             value
          })
       }
     } else {
        if (typeof value === 'object') {
          output.key = key;
          output.children = [];
          generateNestedStructure(value, undefined, output.children);
       } else {
          output.key = key;
          output.value = value;
        }
     }
  });
  return output;
}

console.log(generateNestedStructure(videoInfo, {}));

Answer №2

const DATA = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "job": "Developer"
};

const isObject = (obj) => obj !== null && typeof obj === 'object';

const Process = (data, isNested) => {
    const output = isNested ? [] : {};

    if (data && isObject(data)) {
        Object.keys(data).forEach(key => {
            const value = data[key];
            const val = isObject(value) ? Process(value, true) : value;
            const valueKey = isObject(value) ? "nestedValues" : "singleValue";

            if (isNested) {
                output.push({
                    "key": key,
                    [valueKey]: val
                });
            } else {
                output.key = key;
                output[valueKey] = val;
            }
        })
    }

    return output;
}

const result = Process(DATA);
console.log(JSON.stringify(result, null, 2));

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

Exploring the process of reading a file from a specified file path within a text area using jQuery

I am looking for a way to dynamically read a file based on its path, and then display the contents of that file in a text area. I have attempted to do this with the following code, but it is not working as expected. Here is the code snippet: goog ...

jQuery - can you identify which specific object from the entire set this is?

I am curious if there is a simple method to identify which DOM object I have when it is also part of another set of objects. To illustrate, let's consider the following scenario: There are 5 div elements: <div id="1"></div> <div id="2 ...

Angular nested lists with drag and drop functionality

Recently, I've been working on creating a drag and drop dashboard and stumbled upon an amazing nested list at this link. This particular implementation uses the AngularJs JavaScript framework. However, since I don't have much experience with it, ...

Showing a group of users in real-time as they connect using Socket IO

I've been working on setting up a system in Socket IO to create a list of individuals who join a 'party room'. The plan is to lock the party room once all players are present, and then display views to users. However, I've hit a roadblo ...

Ways to retrieve the current state within a function after invoking the setState method

I'm currently working on a function to store the blogPost object in a document within my Firestore database. The process I have in mind is as follows: Click on the SAVE button and initiate the savePost() function The savePost() function should then ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...

Authentication with Laravel and Vue.js

After successfully implementing Laravel-Vue.js Authentication using Passport API, I am now able to obtain the token and send requests to api/user. Initially, I used the normal authentication process by sending data through a POST request to /login, which r ...

Creating an interface and setting a default value

I am exploring the use of interfaces in my models and want to establish a default value for them. export interface IPerson { id: string; name: string; } class Person implements IPerson { id = ''; name = 'John'; } export cla ...

How should a JavaScript object be properly formatted?

Recently, I created a project using ng-repeat with AngularJS 1.x, and it was smooth sailing. JavaScript: var app = angular.module('myModule', []); app.controller('myController', function() { this.dishes = [ { 'name&a ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...

The dropdown menu in AngularJS is unable to retrieve the selected index

Presently, I have a dropdown menu: <select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;"> ...

There seems to be a glitch in the JavaScript to-do list as it is failing to append new

My attempt at creating a to-do list is not working when I try to add a new entry. Any suggestions? Also, I plan to implement a feature that can calculate the percentage of tasks completed by crossing them off the list. <html> <head> <titl ...

Python Code: Iterate through each column/row appropriately and calculate the difference in value between two CSV files

I am trying to calculate the difference between each value in test.csv and every value in input.csv. For example, subtracting 0.0010 (test.csv) from 0.0023 (input.csv), then from 0.0030 (input.csv), and so on with the subsequent numbers. However, I am curr ...

Ways to narrow down const types

For the given scenario, I aim to enforce a specific format [string, number] for all function returns, while allowing varying input arguments for these functions. Access the Playground here type ReturnFormat = [string, number] type Fn = (...args: any[]) =& ...

When transferring an object from a blade template to a Vue component through props, it may become undefined

I'm facing an issue where I am attempting to send an array from an asynchronous method in the controller to a Vue component using props within a blade template. However, when I try to log it in the Vue component, it shows up as undefined. Here is the ...

Major processing glitch detected in JSON and PHP data handling

I am facing an issue with my PHP page that requests data from another page using JSON. Currently, I have an AJAX call set up like this: $.ajax({ type: "POST", url: "getdata.php", cache:false, data:"lis ...

Adding Intellisense functionality to my IDE: A step-by-step guide

After creating an online IDE using MEAN stack that writes code and provides server-side results, I am looking to enhance it with an intellisense feature similar to VSCode or Atom. Any recommendations on how to achieve this? ...

The jQuery function for $(window).scroll is not functioning as expected

My challenge is getting the scroll to reveal my scrollTop value I've been working with this code: $(document).ready(function(){ console.log('Hello!'); $(window).scroll(function(){ console.log('Scrolling...'); var wScroll = ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...