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

How can I open the Ion-datetime view for the current year without allowing the selection of a specific day?

I am currently troubleshooting an issue with an Ionic date-time picker component. Upon opening the datepicker, it defaults to showing May 2021. As I scroll to the present date, I notice a circle highlighting today's date indicating that it selects th ...

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data: "projectID": 1, "projectName": "XXX", "price": 0. ...

Converting JSON data into an ArrayList for an Expandable ListView in an Android app

I am brand new to Android Programming and I am working on a project that involves displaying JSON data on a Multilevel ExpandableListview. My goal is to display the DivisionName value in the first row (parent) of the list, SubDivisionName value in the seco ...

Enhancing user experience with jQuery tooltips

Having trouble adding a tooltip to a glyphicon. The JSFiddle example provided does not work for me as I am using jQuery to create the HTML elements like this: var trashIcon = $('<i>').addClass('glyphicon glyphicon-trash'); How ...

Using globs to specify files for gulp.src

I'm facing a challenge in setting up a glob array for my JavaScript concatenation build task within the Gulp workflow. The file structure I am working with looks like this: ├── about │ └── about.js ├── assets ├── contact â ...

Output is not being displayed by Ajax

I created a basic PHP code that populates rows and columns with an asterisk (*). To test the PHP code, I entered the URL localhost/squareService.php?rows=3&cols=3 However, when I asked a user to input the number of rows and columns using HTML and Java ...

Using PHP, Ajax, and JavaScript, display interactive data from the server in a dynamic modal popup listbox within a Tinymce-WordPress

Currently, I am in the process of developing a WordPress plugin using TinyMCE. The main functionality involves a button that triggers a popup modal with some list boxes. These list boxes need to be populated with values fetched from the server. To accompli ...

Switch ng-model in Angular to something different

I am looking to transform my own tag into a template <div><input .../><strong>text</strong></div> My goal is to have the same values in both inputs. Check out the plunker here If I change the scope from scope: {value:' ...

Contrast the dissimilarities between JSON and alternative errors

encoder := json.NewEncoder(writer) error := encoder.Encode(struct { RequestMethod string `json:"request_method"` QueryResults []interface{} `json:"query_results"` TimeInCache int `json:"time_in_cache"` }{RequestMethod: pro ...

iOS is causing issues with the JavaScript function and not allowing it to

By creating an NSString that contains JavaScript, I am able to set the e-mail body. NSString * someString =@"<!DOCTYPE html>\n <html>\n <body> \n <h1>My Web Page</h1> \n <p ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', &apos ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

Exploring the ng-repeat directive with an array of objects

In the server response, I have an array of objects that I am trying to iterate over using ng-repeat in order to read each value. While trying to use array[0].value works fine, things are not going as expected when using ng-repeat. Despite all my efforts ...

Turning PHP array into JSON using Zend RPC

Greetings, I am facing a small issue that I need help with. Currently, I am developing a RPC service using ZendFramework and Apigility which requires the response to be in a json array format. Below is the content negotiation code snippet that I have imple ...

My Angular7 app.component.html file is not displaying the routing. What could be the issue?

After implementing the code in app.component.html in Angular 7 like this: <div id="wrapper"> <header id="header-container" class="fullwidth"> <div id="header"> <div class="container"> <div class="left- ...

What is the best way to include a JSON string as an argument in a package.json script entry?

Looking to run UI tests in Puppeteer? You can add a package.json script like this: "scripts": { "test:ui": "cucumber-js --require-module ts-node/register --require test/step_definitions/**/*.ts --require test/support/**/*.ts --world-parameters {\ ...

Converting a JSON object into a format suitable for transmission through AJAX requests

I am attempting to transmit data in a JSobject via AJAX using jQuery. Below is the json object: var cookieData = { 'land' : document.URL, 'ref' : document.referrer }; The object is then stored in a cookie... throu ...

Tips for organizing nodes after converting XML to JSON: Reconstructing the node order

Currently, I am utilizing eXist-db as an XML/TEI database and Angular for website development. The Angular code is requesting data from the eXist-db, and I have chosen to format the response in JSON. At this stage of testing, I believe JSON is the most sui ...