Combine two elements together and display the outcome in json form

There are two objects that need to be summed up and returned in the same format as the original objects stored in a local file.

The first JSON:

{
"data": [{
  "x": "Q1 (J, F, M)",
  "y": [100, 500, 0],
  "tooltip": "this is tooltip"
}, {
  "x": "Q2(A, M, J)",
  "y": [300, 100, 100]
}, {
  "x": "Q3(J, A, S)",
  "y": [351,200,700]
}, {
  "x": "Q4 (Q, N, D)",
  "y": [54, 0, 879]
}]
}

The second JSON:

{
"data": [{
  "x": "Q1 (J, F, M)",
  "y": [100, 500, 200],
  "tooltip": "this is tooltip"
}, {
  "x": "Q2(A, M, J)",
  "y": [300, 100, 100]
}, {
  "x": "Q3(J, A, S)",
  "y": [351,400,555]
}, {
  "x": "Q4 (Q, N, D)",
  "y": [54, 30, 879]
}]
}

The result will be the sum of both objects:

{
"data": [{
  "x": "Q1 (J, F, M)",
  "y": [200, 1000, 200],
  "tooltip": "this is tooltip"
}, {
  "x": "Q2(A, M, J)",
  "y": [600, 200, 200]
}, {
  "x": "Q3(J, A, S)",
  "y": [702,600,1255]
}, {
  "x": "Q4 (Q, N, D)",
  "y": [108, 30, 1758]
}]
}

Looking for a solution to achieve this functionality.

Answer №1

If the arrays always contain the same number of elements (4 in this example, one for each quarter), you can utilize the following ES6 function:

function combineObjects(object1, object2) {
    return object1.data.map( (obj1, index) => Object.assign({}, obj1,  
        { values: obj1.values.map( (value1, j) => value1 + object2.data[index].values[j] ) }
    ));
}

// Sample objects
var object1 = {
    "data": [{
      "key": "Q1",
      "values": [100, 500, 0],
      "info": "tooltip"
    }, {
      "key": "Q2",
      "values": [300, 100, 100]
    }, {
      "key": "Q3",
      "values": [351,200,700]
    }, {
      "key": "Q4",
      "values": [54, 0, 879]
    }]
};

var object2 = {
    "data": [{
      "key": "Q1",
      "values": [100, 500, 200],
      "info": "tooltip"
    }, {
      "key": "Q2",
      "values": [300, 100, 100]
    }, {
      "key": "Q3",
      "values": [351,400,555]
    }, {
      "key": "Q4",
      "values": [54, 30, 879]
    }]
};

console.log(combineObjects(object1, object2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Encountering an issue while executing grunt-contrib-imagemin

Encountering a permissions issue while attempting to execute the grunt-contrib-imagemin script. The installation of grunt-contrib-imagemin was done as follows: npm install --save-dev grunt-contrib-imagemin Node and npm are both installed in my local user ...

Passing arguments to an external function in jQuery from a dynamically loaded Ajax page

Despite its confusing title, the issue at hand is actually quite simple. My homepage contains a script that loads an external PHP file for a specific section of my website. Within this PHP file, I need to call a function from the main JavaScript file (th ...

Enhance the jQueryUI progress bar by dynamically updating it with inner HTML data

I am working on implementing a jQueryUI progress bar and facing some challenges. Here is the basic code for the progress bar: <script> $(function() { $("#progressbar").progressbar({ value: 50, }); }); </script& ...

In order to achieve a sliding effect for the second div, it can be programmed to

Currently, I am working on implementing hide and show functionality in my project. However, I have come across a bug in my code that I need assistance with. When clicking on the first div element, the content opens from bottom to top instead of the desired ...

Retrieve information from an API and assign the corresponding data points to the graph using Material UI and React

I have 4 different APIs that I need to interact with in order to fetch specific details and visualize them on a bar graph. The data should be organized based on the name, where the x-axis represents the names and the y-axis represents the details (with 4 b ...

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

"If the radio button is selected, ensure that the element has the required attribute added

In my form, I have radio buttons and an input field. When any of the three top radio buttons are checked, I need to make the input field required. Here is my code: <ng-form name="addShareholderForm"> <form name="form.addForm" class="form-validati ...

A guide on verifying the username, password, and chosen role from a database through the use of javascript/ajax or alternative validation methods

If the user's name, password, or role is incorrect, I want to display an error message using validations like AJAX/JavaScript. index.php <html> <head> </head> <body> <style> body { wi ...

Is there a way to remove a value from the search bar while updating the table at the same time?

Although I can successfully search the table based on the values in my search bar, I am having trouble with updating the state when deleting a value. To see my code in action, check out my sandbox here. ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...

Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object: var obj = { arr1: [0, 1, 2], arr2: [1, 2, 3], arr3: [2, 3, 4] }; After pop()ing values from the arrays within the object, I ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

Accessing PHP variables in JavaScript

Hi there, I am new to all this. I am trying to figure out how to use a PHP variable in JavaScript. Here is a snippet of my code (popup.php): <?php $id_user = $this->session->userdata('id'); ?> <script type="text/javascript"> ...

Obtaining form data from connected drop-down menus and sending it to PHP

My webpage contains a form with 2 dependent drop-down lists. When a user selects a value from the first list, it populates the second list for the user to make another selection. However, when I try to submit the form data to a PHP page to insert into a M ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...

Guide to filtering an array within ag-grid when defining a column

After switching from using DataTable to ag-grid, I encountered a challenge. In DataTable, I accessed the first element from the attributes array where typeName='ItemType'. Now, I am looking to achieve the same functionality in ag-grid. Any sugges ...