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

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

When the return false statement is included, the form fails to submit and instead refreshes on the current page

I recently discussed an issue regarding triggering a dialog box before confirming a submit action. Unfortunately, after implementing this, the document no longer submits when expected. Instead, it just remains on the same page with the same settings. I h ...

Is there a simpler and more refined approach for handling Observables within RxJS pipelines?

Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer ...

Using jQuery to send information to PHP via an AJAX request

When attempting to use jQuery to send form data to a PHP file, nothing happens when the button is pressed. The jQuery code snippet: $(document).ready(function(){ $("#daily_user_but").click(function(){ $('#result').html('<im ...

Sending non UTF-8 encoded JSON using Python Requests

When sending data to a web service connected to a MySQL server set up with latin-1 collation for its tables, I encountered an issue. The web service is designed to receive JSON payloads, but it does not encode the data properly to save in the database, res ...

The concept of 'this' remains undefined when using a TypeScript Property Decorator

I've been delving into TypeScript decorators focusing on properties, and I crafted the following snippet inspired by various examples: decorator.ts export function logProperty(target: any, key: string) { let val = this[key]; const getter = () ...

Schema Connections in Kendo Diagram

I am currently experimenting with the Telerik Kendo diagram in an attempt to create a visual representation. Due to the fact that I am retrieving all shapes and their connections from my database, I encountered an issue where the attributes of my data sour ...

What steps should be taken to fix the sinopia installation error?

While operating on redhat5.9, I encountered an exception related to 'make'. I am curious about what they are trying to create. It seems like it's related to JavaScript. [root@xxxx bin]# npm install -g sinopia --python=/usr/local/clo/ven/pyt ...

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

Explore the latest update in the AngularJS single page application that introduces a new feature specifically designed for the initial login

Our AngularJS single page application has a new feature that we are ready to launch for customer use. We want to inform the logged in user about this new feature so they can start using it. We are looking for a small animated information symbol with a too ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...

AngularJS seems to be failing to display the initial option in the input select field

When using Angularjs, binding an input select to the model results in a new empty option being created <option value="? undefined:undefined ?"></option> Here is an example of the code: <select name="category" ng-model="hotspot.category"&g ...

Identica tweet tracker at its finest!

Is there a way to find out how many times a specific URL has been shared on identi.ca, status.net, or similar platforms? While there are services available for retrieving this information on Twitter. Twitter itself: Tweetmeme: Topsy: ? I specificall ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...

React component showcasing live data based on the URL's input

I'm looking to develop a dynamic component that can retrieve and display data from a JSON file based on the URL path, rather than creating separate pages for each dataset. For instance: https://jsonplaceholder.typicode.com/posts If the page route is ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Enhancing ng-include in AngularJS upon user authentication (or exploring alternative solutions)

As I delve into learning Angular, I've embarked on a project to develop an app that controls content access based on authentication. The authentication aspect is functioning smoothly (with the aid of the Laravel PHP framework), but I'm encounteri ...

The active tab will dynamically update, however, clicking anywhere on the page will always bring you back to the first tab as

My view includes the following tabs: <div class="tabbable"> <ul class="nav nav-tabs padding-18"> <li class="active"> <a aria-expanded="false" data-toggle="tab" href="#Tab1"> <i class="green ac ...