Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this:

var jsObj = {
        "templates": {
            "form0": {
                "ID": "MyAlertNew",
                "isVisible": "true",
                "children": [
                    {
                        "-type": "kButton3",
                        "ID": "myButtonID1",
                        "isVisible": "true",
                        "onClick": "onClickMethod",
                        "paddings": {
                            "left": "0",
                            "right": "0",
                            "top": "3",
                            "bottom": "3",
                            "unit": "%"
                        },
                        "text": "dynamic text in file"
                    },
                    {
                        "-type": "kButton1",
                        "ID": "btnAlign2",
                        "visible": "true",
                        "margins": {
                            "left": "0",
                            "right": "0",
                            "top": "0",
                            "bottom": "0",
                            "unit": "%"
                        }
                    }

                ]
            },
            "form1": {
                "ID": "frmNewPOC1",
                "isVisible": "true",
                "children": [
                    {
                        "-type": "kButton3",
                        "ID": "btnAlign",
                        "isVisible": "true",
                        "onClick": "onClickMethod",
                        "paddings": {
                            "left": "0",
                            "right": "0",
                            "top": "3",
                            "bottom": "3",
                            "unit": "%"
                        },
                        "text": "in diff form"
                    },
                    {
                        "-type": "kButton1",
                        "ID": "btnAlignTest",
                        "visible": "true",
                        "margins": {
                            "left": "0",
                            "right": "0",
                            "top": "0",
                            "bottom": "0",
                            "unit": "%"
                        },
                        "text": "in My Form"
                    }  
                ]
            }
        }
    };

In order to filter it as shown below:

objnew ={
        "MyAlertNew":{
            "isVisible": "true"
        },
        "myButtonID1":{
            "isVisible": "true",
            "onClick": "onClickMethod",
            "paddings": {
                "left": "0",
                "right": "0",
                "top": "3",
                "bottom": "3",
                "unit": "%"
            },
            "text": "dynamic text in file"
        },
        "btnAlign2":{
            "visible": "true",
            "margins": {
                "left": "0",
                "right": "0",
                "top": "0",
                "bottom": "0",
                "unit": "%"
            }
        },
        "frmNewPOC1":{
            "isVisible": "true"
        },
        "btnAlign":{
            "isVisible": "true",
            "onClick": "onClickMethod",
            "paddings": {
                "left": "0",
                "right": "0",
                "top": "3",
                "bottom": "3",
                "unit": "%"
            },
            "text": "in diff form"
        },
        "btnAlignTest":{
            "visible": "true",
            "margins": {
                "left": "0",
                "right": "0",
                "top": "0",
                "bottom": "0",
                "unit": "%"
            },
            "text": "in My Form"
        }
    }

I have attempted the code below but haven't achieved success yet

   testObj = jsObj.templates;
        var idObj = [];
        var widgetProp =[];
        var ID ;
        function parseMyObj(testObj){
            for(x in testObj){

                if(typeof testObj[x] == "object"){
                    //widgetProp[]
                    parseMyObj(testObj[x]);
                }
                else if(x=='ID'){
                    ID = testObj[x];  
                    idObj.push(testObj[x]); 

                }
                else{
                    widgetProp.push(x:testObj[x]);
                }
            }
        }
        parseMyObj(testObj);
        console.log(widgetProp);
        console.log(JSON.stringify(idObj));

If anyone could provide assistance, it would be greatly appreciated. Thank you in advance.

Answer №1

A basic algorithm is presented here, assuming that the key names ID and children will remain constant.

  1. Start by creating an empty object called N
  2. Iterate through the keys and values of object O
    • If the value is an object, update O to this object and repeat step 2.
    • If the key is children, iterate through each child and update O to the child before revisiting step 2.
    • If the key is ID
      1. Save the value as name
      2. Create a new object named X.
      3. Transfer all key-value pairs from O to X</code except for <code>ID and children.
      4. Assign the created object to the key name within your object N

Below is a simple implementation (not very flexible) of the algorithm described above.

var createFormattedObject = function(baseObject, formattedObject) {
  formattedObject = formattedObject || {};

  for(var key in baseObject) {
    if(!baseObject.hasOwnProperty(key)) {
      continue;
    }
    var value = baseObject[key];

    if(key === "ID") {
      formattedObject[value] = {};
      for(var k in baseObject) {
        if(k !== "ID" && k !== "children") {
          formattedObject[value][k] = baseObject[k];
        }
      }
    } else if(key === "children") {
      for(var i = 0; i < value.length; i++) {
        createFormattedObject(value[i], formattedObject);
      }
    } else if(value instanceof Object) {
      createFormattedObject(value, formattedObject);
    }
  }

  return formattedObject;
};

Please note that the second parameter is primarily used for recursion purposes and may not be necessary when calling the function.

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

Converting a JSON array to an array using SwiftyJSON

I'm dealing with a JSON array named var array: [JSON] = []. I want to convert this into a standard array in order to filter and manipulate the data. Can anyone suggest the best approach for achieving this? One attempt I made was using let filteredArr ...

When trying to insert JavaScript into the console, a section of the code fails to execute

In this code snippet, I am fetching the most common English words from Wikipedia, extracting all the words from the page, and then filtering out the commonly used words: // get table data from most common words var arr = []; $.ajax({ url: 'https:/ ...

Encountered an error while trying to access an undefined property during an Angular Karma

I'm currently working on testing a service function that involves multiple $http.get() calls. The function being tested returns a promise but the test is failing with an error stating response is undefined. Below is the test script: it('should ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

Good day extract a collection of articles

I am trying to parse out the date and full URL from articles. const cheerio = require('cheerio'); const request = require('request'); const resolveRelative = require('resolve-relative-url'); request('https://www.m ...

Dealing with Oversized Images in Jcrop: Tips and Tricks

Utilizing Jcrop for cropping images, everything runs smoothly with small images. However, when I attempt to use large images like 2080x2080 or 1600x1600, it takes up the entire screen and cannot be controlled by CSS properties such as width and height in t ...

Exploring External Functions in Angular Beyond the Library

Transitioning from standard JavaScript to Angular has been a bit challenging for me, especially when working with the Google Places library (or any other asynchronous callback). Here is the code snippet: var sparkApp = angular.module('sparkApp' ...

Embed a function within a string literal and pass it to another component

Is there a way to pass a function defined in actions to an element? Reducer case 'UPDATE_HEADER': return Object.assign({}, state, { headerChildren: state.headerChildren.concat([action.child]) }); Action.js export const deleteH ...

Setting Start and End Dates in Bootstrap Vue Datepicker to Ensure End Date is After Start Date

My Vue.js form includes two BootstrapVue datepickers for holiday management. Users can define the start date and end date of their holiday, with the condition that the end date must be equal to or greater than the start date. Here is my current implementat ...

Socket.io in Express is already assigned to another address

I'm having trouble getting my app to connect with Socket.io via websockets. Each time I attempt to run this code snippet, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 Despite checking for any other process ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

What is the best way to resize a div located below a dynamic div in order to occupy the available space?

My website has a dynamic div1 and a scrollable table inside div2. I need the div2 to take up the remaining height of the window, while ensuring all divs remain responsive. I've tried using JavaScript to calculate and adjust the heights on window loa ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

Struggling with smoothly transitioning an image into view using CSS and JavaScript

I'm currently experimenting with creating a cool effect on my website where an image fades in and moves up as the user scrolls it into view. I've included the code I have so far below, but unfortunately, I keep getting a 404 error when trying to ...

Exploring the functionality of placeholders within jQuery

I am trying to create a customizable text template where I can insert placeholders and then fill those placeholders with data to use on my page. For example: var template = '<div class="persons">'; template += '<p> <span clas ...

Retrieve Cookie from a designated domain using Express

I am currently working on a React application that communicates with a Node/Express backend. To ensure the validity of requests, I am sending a cookie created by react-cookie from the React app to the Express app. To avoid issues related to naming conflict ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Syntax error occurs while attempting to render the return statement in a React Component

Just starting out with React and encountering a syntax issue that has me stumped. I'm working on a React Component and I thought I had the opening/closing { & }'s correct, but clearly there's something missing based on the error message it&a ...