Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with:

{
  "status": "CREATED",
  "overrides": {
    "name": "test_override"
  },
  "package_name": "test",
  "name": "app1",
  "defaults": {
    "job": {
      "example": {
        "executors_num": "2",
        "freq_in_mins": "180",
        "executors_mem": "256M",
        "job_name": "batch_example"
      }
    }
  }
}

The goal is to transform the above JSON object into a structure like this. Essentially, adding an array to each nested object:

{
  "children": [
    {
      "status": "CREATED"
    },
    {
      "obj": "overrides",
      "children": [
        {
          "name": "test_override"
        }
        ]
        },
        {
          "package_name": "test"
        },
        {
          "name": "app1"
        },
        {
          "obj": "defaults",
          "children": [
          {
           "obj": "job",
           "children": [
           {
            "obj": "example",
            "children": [
            {
              "executors_num": "2",
              "freq_in_mins": "180",
              "executors_mem": "256M",
              "job_name": "batch_example"
            }]
          }]
        }]
      }
    ]
}

Below is some code snippet that I have been using:

function traverse(o, d) {
  for (i in o) {
    if (typeof(o[i])=="object") {
      console.log(i, o[i]);
      // considering only 'default' obj for now
      if(i === 'defaults') {
        d.children.push( {obj: i, "children" :[ o[i] ]});
      }
      traverse(o[i], d);
    }
  }
  return d;
}   

However, the current output does not include the necessary arrays within nested objects:

{"children":[{"obj":"defaults",
"children":[{"job":{"example":
{"executors_num":"2","freq_in_mins":"180","executors_mem":"256M","job_name":"batch_example"}}}]}]}

I seem to be stuck at this point and unsure how to incorporate the children array into every nested object. Any suggestions?

Answer №1

Here we have a recursive function that checks if the key of an object is itself an object, and if so, it calls itself.

var data = {
  "status": "FAILED",
  "overrides": {
    "name": "test_override"
  },
  "package_name": "test",
  "name": "app2",
  "defaults": {
    "job": {
      "example": {
        "executors_num": "3",
        "freq_in_mins": "240",
        "executors_mem": "512M",
        "job_name": "batch_example_v2"
      }
    }
  }
}

function convertToArray(obj){
  var result = {children:[]}
   Object.keys(obj).forEach(function(key){
     var childObject = {};
     
      if(typeof obj[key] === 'object'){
       childObject[key] = convertToArray(obj[key])
      }
      else{
        childObject[key] = obj[key]  
      }
     result.children.push(childObject)
   })
   return result;
}

document.write(JSON.stringify(convertToArray(data)))

Answer №2

Here is a new approach that involves creating a separate object for each property within the children array.

function restructure(object, result, key) {
    if (typeof object === 'object') {
        result.obj = key;
        result.children = [];
        Object.keys(object).forEach(function (k) {
            var o = {};
            result.children.push(o);
            restructure(object[k], o, k);
        });
    } else {
        result[key] = object;
    }
}

var dataObject = { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name":"test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "freq_in_mins": "180", "executors_mem": "256M", "job_name": "batch_example"}}}},
newDataObject = {};

restructure(dataObject, newDataObject);
document.write('<pre>' + JSON.stringify(newDataObject, 0, 4) + '</pre>');

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

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Enhancing React Native experience by dynamically editing array elements

This code block defines the state of my program, including an array: this.state = { arr: [{ arrid: 0, arrEmail: '', arrName: '', arrPhone: '' }], id: 0, email: "", isChecked: true, name: "", phon ...

When the Button is clicked, the component utilizing the Router fails to appear

My current task involves creating a page where users can choose between two options: Button 1 leads to TestOption.js, while Button 2 redirects to TestOption2 (currently using TestOption for testing purposes). The default landing page is SelectionPage. The ...

Looking to incorporate an additional column 'LastName' that can be used for filtering in the Angular data table code. This column will be included if it is present in the data

function applyFilter(filterValue: string) { filterValue = filterValue.toLowerCase(); --- return filtered result return this.dataSet.filter( (item: any) => item.name ? item.name.toLowerCase(). ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

The Node.js script functions correctly on the first run but encounters failure in subsequent executions

I am in need of a Node.js script that can perform the following tasks: 1 - Trigger when an image is added to a specific S3 bucket. 2 - Generate a thumbnail of that image (360x203 pixels). 3 - Store a copy of the thumbnail in a separate S3 directory. ...

Can a function be called when using ng-options with AngularJS select?

Here is some HTML code <select ng-model="selectedMarker" ng-options="shape.text for shape in Selects('shapes')"> </select> And below is the JavaScript code angular.module('todo', ['ionic']) . ...

Transforming JSON data into a SQL Server 2016 table

I have been working on a Web project where the client application communicates with the database through JSONs. In the beginning, we used SQL Server 2012, which did not support JSON. To work around this limitation, we implemented a Stored Function to hand ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

How can you retrieve an array of multiple property values from a collection of dynamic objects?

I am currently working with a dynamic JavaScript object array that has varying structures. For example: var someJsonArray = [ {point: 100, level: 3}, {point: 100, level: 3}, {point: 300, level: 6} ]; At times, it may have a different combination lik ...

Load styles in Nuxt asynchronously to improve performance

Is there a way to load styles asynchronously on the website or insert them in the footer? I am currently using Nuxt version 2.0.0 Here's what I have tried so far: Adding a plugin in webpack called async-stylesheet-webpack-plugin. However, this res ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Guide to triggering an event when two distinct keys are pressed simultaneously (Using HTML5 and Javascript)

I'm looking to have my character jump whenever I press any key on the keyboard. Is there a method to achieve this using "case..." functions? Thanks! Jordan ...

Troubleshooting JSON compatibility problem in Django with Internet Explorer

Struggling with JSON compatibility issues in Internet Explorer (IE9). I've scoured the internet and tried various solutions to no avail. Decided it was time to create a Stack Overflow account and pose my first question. My JSON and jQuery/AJAX-based ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

The pattern() and onkeyup() functions are unable to function simultaneously

When trying to display a certain password pattern using regex while typing in the fields, I encountered a problem. The onkeyup() function works for checking if both passwords match, but it causes the pattern info box not to appear anymore. I'm curiou ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

Retaining only the final record, a JSON object within a for loop

Looking for a solution to this issue: JSONObject output = new JSONObject(); JSONObject elements = new JSONObject(); JSONArray jsonArrayOutput = new JSONArray(); ArrayList<String> name = ArrayList<String>(); for (int i=0 ; i<name.size() ; ...

Prevent tab switching from occurring by disabling click functionality on tabs

I've got different tabs set up in a similar way <md-tabs md-selected="selectedTab()"> <md-tab label="General"></md-tab> <md-tab label="Type"></md-tab> <md-tab label="Details"></md-tab> </md-tab ...

The integration between Javascript, PHP, and SQL Server does not display the retrieved data

I am a beginner in PHP and have limited knowledge of Javascript. I am attempting to create a chronometer where the time limit is retrieved from a SQL SERVER database. However, when I assign the value obtained in PHP to a Javascript variable, it returns -1. ...