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

How to Detect Font Resizing in Google Web Toolkit (GWT)

I am trying to find a way in GWT to capture the font resize event that occurs when the user changes the size of the font by using Ctrl-Mouse Scroll or going to View -> Zoom. I have searched on Google and looked on StackOverflow but haven't found an ...

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

Is there a way to send JSON using ExpressJS in UTF-8 encoding?

Currently facing an issue with my new web app that I haven't encountered in the past. Experimenting with a simple code snippet like this: var jsonToSend = {hello: "woørld"}; app.get('/someUrl', function(req, res) { res.setHeader('Co ...

Executing functions and setting element values upon loading in Javascript

I am currently working on updating a small Javascript function that assigns an active class to the parent <div> of a group of radio buttons when the page loads and also when there's a change event. The existing function looks like this: functi ...

Leveraging underscore.js for null verification

let name = "someName"; if(name !== null) { // perform some action } Currently, I am utilizing http://underscorejs.org/#isNull. How can I achieve the same functionality using underscore.js? Is there any noticeable performance enhance ...

Using jQuery to trigger alert only once variable has been updated

I have a question that may seem too basic, but I can't find the solution. How do I make sure that the variables are updated before triggering the alert? I've heard about using callbacks, but in this case, there are two functions and I'm not ...

What is the best way to handle multiple JSON data using jQuery?

Understanding how to utilize jquery for parsing simple json is a valuable skill. json { "Symbol": "AAL.L", "Name": "ANGLO AMERICAN", "Last": "3061.50", "Date": "7/26/2011", "Time": "11:35am", "Change": "+3 ...

Submitting a POST request to paginate and sort the results

Currently, I have a system in place where a GET request is used to query the database and display the results. While this method works well, I am looking to transition it into a POST request. This would allow for a more flexible approach by handling JSON b ...

Using JSON Schema to validate multiple occurrences of a property

I'm currently working on defining a JSON schema that includes multiple properties for instances of the same object in a Java application endpoint. For instance, here is a simple example of what I'm aiming to accomplish: { "$schema": "http://jso ...

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

What is the best way to tally the frequency of words in a collection of URLs using JavaScript?

I have a JSON object in WordPress that contains a list of URLs. I would like to determine the frequency of occurrence of the second part of each URL. Currently, the code snippet below is able to extract the remaining part of the URL after the prefix https ...

Injecting dynamic data into a function parameter with Angular 1 Interpolation

In my code, I have a feature that alters the text displayed on a button depending on certain conditions. $scope.text = 'Wait'; if(Number($scope.x) == Number($scope.y)) $scope.text = 'Go' else if(Number($scope.x) < Number($scope ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

Are the elements in the second array the result of squaring each element in the first array? (CODEWARS)

I am currently working on a 6kyu challenge on codewars and I've encountered a frustrating issue that I can't seem to figure out. The task at hand involves comparing two arrays, a and b, to determine if they have the same elements with the same mu ...

Performing pandas.json_normalize on nested JSON data without a consistent record_path

Currently, I am facing a challenge in converting a large JSON file to CSV format. The specific issue arises when attempting to sort data on the Spreadsheet because the field required for sorting is consolidated into one cell during the conversion process. ...

Converting a date string from JSON into a time span: A step-by-step guide

I have a JSON response with a time value in the format of "sun dd/mm/yyyy - HH:mm" that I need to convert into a time span like "10 min ago, 2 days ago..." To do this, I created a method that converts the given date and time string into the format "X Hours ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

Utilize Gson to precisely format double values up to 4 decimal places

Is there a way to use Gson to format double values so that they are rounded or truncated to 4 decimal places? ...