What is the best way to combine and merge JSON objects that consist of multiple sub-objects?

I am working with a JSON response that contains multiple objects consisting of two main objects - datacenter and environment:

"deployments": [
                    {
                        "datacenter": {
                            "title": "euw1",
                            "name": "foodatacenter",
                            "revision": "0",
                            "state": "Active"
                        },
                        "environment": {
                            "clusterId": "AAA",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active",

                        }
                    },
                    {
                        "datacenter": {
                            "title": "apc1",
                            "name": "foodatacenter",
                            "revision": "0",
                            "state": "Active"
                        },
                        "environment": {
                            "clusterId": "BBB",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active"
                        }
                    },
                    {
                        "datacenter": {
                            "title": "euw1",
                            "name": "foodatacenter",
                            "revision": "0",
                            "state": "Active"
                        },
                        "environment": {
                            "clusterId": "BBB",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active"
                        }
                    },
                     {
                        "datacenter": {
                            "title": "use1",
                            "name": "foodatacenter",
                            "revision": "0",
                            "state": "Active"
                        },
                        "environment": {
                            "clusterId": "AAA",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active"
                        }
                    },
                    {
                        "datacenter": {
                            "title": "use2",
                            "name": "foodatacenter",
                            "revision": "0",
                            "state": "Active"
                        },
                        "environment": {
                            "clusterId": "AAA",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active"
                        }
                    },
    ]

I need to find the best way to group these objects by environment using JavaScript. The ideal result should look like this:

"deployments": [
                    {
                            "clusterId": "AAA",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active",
                            "datacenters":[
                               {
                                 "title": "euw1",
                                 "name": "foodatacenter",
                                 "revision": "0",
                                 "state": "Active"
                               },
                               {
                                 "title": "use1",
                                 "name": "foodatacenter",
                                 "revision": "0",
                                 "state": "Active"
                               },
                               {
                                 "title": "use2",
                                 "name": "foodatacenter",
                                 "revision": "0",
                                 "state": "Active"
                               },
                           ]
                    },
                    {
                            "clusterId": "BBB",
                            "name": "foocluster",
                            "revision": "0",
                            "state": "Active",
                            "datacenters":[
                               {
                                 "title": "euw1",
                                 "name": "foodatacenter",
                                 "revision": "0",
                                 "state": "Active"
                               },
                               {
                                 "title": "apc1",
                                 "name": "foodatacenter",
                                 "revision": "0",
                                 "state": "Active"
                               }
                           ]
                    }

    ]

Your assistance on how to achieve this would be greatly appreciated. Thank you for your help!

Answer №1

To solve this problem, the only solution seems to be iterating through the array and organizing datacenter objects according to their respective environment. Here is a draft of how this could be achieved in pseudo-code:

  1. for each object in the array
    1. key = JSON.stringify(o.environment);
    2. search for key in a dictionary.
    3. if key is not found, create a new entry with an empty array as value
    4. add datacenter to the corresponding array under key
  2. initialize a result array
  3. for each entry in the dictionary
    1. construct an environment object using the key
    2. create a new item in the result array containing fields from environment and the associated datacenter objects.

Answer №2

Utilizing the array#reduce method allows you to categorize data by environment and clusterId, store it in an object, aggregate all datacenter entries under the same clusterId, and then retrieve the values from the object.

const information = {"deployments": [{ "datacenter": { "title": "euw1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "AAA", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "apc1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "BBB", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "euw1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "BBB", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "use1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "AAA", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "use2", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "AAA", "name": "foocluster", "revision": "0", "state": "Active" } }] },
    result = Object.values(information.deployments.reduce((accumulator, { datacenter, environment }) => {
      const key = environment.clusterId;
      accumulator[key] = accumulator[key] || {...environment, datacenters: []};
      accumulator[key].datacenters.push({...datacenter});
      return accumulator;
    }, {}));
console.log(result);

"use strict";

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var info = { "deployments": [{ "datacenter": { "title": "euw1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "AAA", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "apc1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "BBB", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "euw1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "BBB", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "use1", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "AAA", "name": "foocluster", "revision": "0", "state": "Active" } }, { "datacenter": { "title": "use2", "name": "foodatacenter", "revision": "0", "state": "Active" }, "environment": { "clusterId": "AAA", "name": "foocluster", "revision": "0", "state": "Active" } }] },
    outcome = Object.values(info.deployments.reduce(function (accumulator, obj) {
  var datacenter = obj.datacenter,
      environment = obj.environment;

  var key = environment.clusterId;
  accumulator[key] = accumulator[key] || _extends({}, environment, { datacenters: [] });
  accumulator[key].datacenters.push(_extends({}, datacenter));
  return accumulator;
}, {}));
console.log(outcome);

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

jQuery - How come my string values are getting cut off?

It's been a while since I last worked with jQuery, and I seem to be missing something obvious that's affecting my calculations. I have various text boxes for Weight, Moisture %, and Number of Filled Squares, as well as a multi-select option for ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

Populating a Listview in jqueryMobile with dynamic elements

I am struggling with my listview. Whenever I try to add or remove items from the list, the jquery mobile styling does not get applied to the new content that is added. <ul data-role="listview" id="contributionList"> <li id="l1"><a>5. ...

Tips for preventing repetition in http subscribe blocks across various components

Imagine a scenario where there is a service used for making HTTP request calls. There are two different components (which could be more than two) that need to send the same request using the same observables via this service. After receiving the result, it ...

Is there a way for the React select component to adjust its width automatically based on the label size?

After defining a React select component, it looks like this: <FormControl> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id=&quo ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

The data payload needed for sending a POST request in JSON format

I am in the process of constructing a body for a POST request relativeurl := "this-is-a-test-url" postBody := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"rela ...

Accept JSON data within a node server utilizing express

I am encountering an issue with sending a JSON object to my node server in Java. I am trying to display the value in the server console but it is showing up as "undefined." Can someone provide guidance on how to properly retrieve the JSON object and parse ...

Error in Webpack 5: Main module not found - Unable to locate './src'

When trying to build only Express and gql server-related files separately using webpack5, an error occurs during the process. ERROR in main Module not found: Error: Can't resolve './src' in '/Users/leedonghee/Dropbox/Project/observe ...

Issue with triggering the change event for <select> tag

Whenever the selected value of the drop down changes, the following code does not work as expected. Please make corrections if any errors are present. <!doctype html> <html lang="en"> <head> <meta charset="utf-8</scri ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Injecting dynamic variables into JSON objects using JavaScript

I am facing a challenge with populating values dynamically from an array of elements. Below is the primary array that I am working with. list = [{name: 'm1'}, {name: 'm2'},{name: 'm3'},{name: 'm4'},{name: 'm5&ap ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

Repeated firing of jQuery's Ajaxstop within a click event

When using the quantity plus button on the woocommerce cart page and reaching maximum stock, I want to display a notice. However, due to an auto update on the cart, I have to wait for the ajax load to complete before showing the notice. My script revealed ...

What is the best way to run a series of basic commands in Node.js in sequence

Is there a way to execute 4 bash commands sequentially in nodejs? set +o history sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js sed -i 's/&& !this.peekStartsWith('\/\/ ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...

Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank. The SELECT queries in use are as follows: -- Retrieve all users S ...

Unable to fetch local file using ajax from a local HTML page

According to Same Origin Policy, the SOP should not be applied to the file:// protocol. However, I'm having trouble with my code. I am running a testing page from my local system, and both when I try to access abc.txt in the same directory as the HTML ...