Combining two arrays filled with objects to form a collection of Objects on a Map

In my JavaScript code, I'm receiving data from a WebService that looks like this:

{
  "fire": {
    "totalOccurence": 2,
    "statsByCustomer": [
      {
        "idCustomer": 1,
        "occurence": 1
      },
      {
        "idCustomer": 2,
        "occurence": 1
      }
    ]
  },
  "flood": {
    "totalOccurence": 1,
    "statsByCustomer": [
      {
        "idCustomer": 1,
        "occurence": 1
      }
    ]
  }
}

I need to create the following object based on this data:

{
  "1": {
    "fire": 1,
    "flood": 1
  },
  "2": {
    "fire": 1,
    "flood": 0
  }
}

Currently, I am using multiple forEach loops to format the data, but I believe there might be a better and more efficient way to achieve this. PS: The customer Id should be used as the key in the result map.

If you have any suggestions on how to optimize this process, I would greatly appreciate your input!

Thank you for your assistance!

Answer №1

To achieve the desired outcome, you can start by iterating through the keys of the outer object and then the inner arrays. If a result object is not already present, create one that includes the necessary keys with initial values set to zero.

var data = { fire: { totalOccurrence: 2, statsByCustomer: [{ idCustomer: 1, occurrence: 1 }, { idCustomer: 2, occurrence: 1 }] }, flood: { totalOccurrence: 1, statsByCustomer: [{ idCustomer: 1, occurrence: 1 }] } },
    result = {},
    keys = Object.keys(data);

keys.forEach(function (k) {
    data[k].statsByCustomer.forEach(function (a) {
        if (!result[a.idCustomer]) {
            result[a.idCustomer] = {};
            keys.forEach(function (kk) {
                result[a.idCustomer][kk] = 0;
            });
        }
        result[a.idCustomer][k] += a.occurrence;
    });
});

console.log(result);
.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

Directive that accesses an element and adds an event listener

I'm in need of developing an attribute directive using Angular 1.5.5 that will restrict inputs based on the keypress event of a text box. The desired output should be like this: <input type="number" name="age" id="age" restrict-char="['e&apos ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

Displaying tab content in AngularJS from a dynamic array

I am currently working on my very first Angular SPA project. Within a form, I have implemented three tabs and would like each tab to display its content only when selected. The contents of the tabs are stored in an array within the controller. I have spent ...

Obtain the IDs of the previous and next list items if they exist?

Hey there friends, I've hit a roadblock and could really use your help. I'm trying to figure out how to get the previous and next list items in a specific scenario. Let's say I have a ul with three li elements, and the second one is currentl ...

Is there a way to access the value of a variable in Express that is stored in a different file?

Looking for a way to fetch the value of a variable that is located inside app.use? chatbot.js: const express = require('express'); const app = express.Router(); app.use(['/chat', '/chatbot'], (req, res, next) => { const ...

A guide on displaying complete text as the container width expands using Tailwind CSS and Next.js

On my platform, users have the ability to create albums and give them names of any length. When a user creates an album, it generates a div along with a link (the album's name) and two icons. I am looking to implement a feature where if a user enters ...

jQuery failing to transmit JSON in AJAX POST call

I'm a bit perplexed at the moment, as I'm attempting to send data to my Node.js server using the code snippet below: $.ajax({type:'POST', url:'/map', data:'type=line&geometry='+str, succe ...

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...

Issues with Jquery/AJAX function not responding to onChange Event

I am currently working on a project where I need to populate a dropdown menu based on the value selected from another dropdown. However, I am encountering an issue with the function that I am trying to call in the onChange event of the select tag. This is ...

The Battle of Brainpower: Smarty vs. JavaScript/AJAX

One question I have is: Is there a specific guideline or convention for determining when to use "Smarty templating" versus using JavaScript Ajax calls to generate content? I have the ability to generate content dynamically using Ajax/JavaScript calls. Whi ...

Designing a versatile pop-up window with jQuery or JavaScript that functions seamlessly across all web browsers

I've encountered an issue with my code where it displays a popup message correctly in Chrome, but when testing it on Firefox and Edge, it creates a strange box at the end of the page instead. Here is the code snippet I'm referring to: var iframe ...

Modify URL parameters using history.pushState()

Utilizing history.pushState, I am adding several parameters to the current page URL after performing an AJAX request. Now, based on user interaction on the same page, I need to update the URL once again with either the same set of parameters or additional ...

What is a sophisticated method to hide an element from view?

My dilemma involves a dropdown menu and a list of elements that are initially set to hidden using CSS. When an item is selected from the dropdown, it becomes visible. However, I am struggling with finding a way to revert the previously selected element b ...

Managing various events in AngularJSHandling multiple events in AngularJS

In my Angular application, I am updating a div when a tag is clicked. Now, I also need to change the route when the tag is clicked. How can I achieve this in AngularJS? ...

evaluation of three variables using short-circuit logic

I was quite surprised by the outcome of the code I wrote. It seemed like it wouldn't work because it was checking if something is not running and the ID matches a specific one, then executing the code regardless of the break size limit: if(!isRunning ...

Is there a tool available on the command line to detect simple Javascript syntax mistakes?

Is there a command-line tool in Linux that can identify basic syntax errors and compile time errors in JavaScript files intended for web browsers? Usually, I write my JavaScript code alongside server-side languages like Ruby or Perl. It would be beneficia ...

Adjust the text area to automatically expand or shrink based on the text it contains

Is there a way to automatically adjust the size of a textarea based on its content? Here is the code I am currently using for this purpose: var element = document.getElementById(event.target.id); var content = $(this).val().trim(); if (content == "") { ...

learning how to combine two json arrays of objects and showcase them in a react component

What is the best way to combine this data and present it in a table with a map using React? The text will be in the first column and the count in the second. const handleSubmit = async (event) => { event.preventDefault(); let URL1 = " ...

Utilizing a for loop to iterate through an array based on its length

Just delving into the world of JavaScript and recently grasped the concept of For loops. I have a variable that holds an array with a list of first names, and my goal is to add last names to each of them. Here's the code snippet I came up with: l ...

Spring MVC is set to generate JSON data but ends up displaying a web page instead

I have a method in my controller that produces a JSON payload using Spring MVC. @RequestMapping(value = "/MerchantMonitoringAPI", method = RequestMethod.GET,produces = "application/json") public String MerchantMonitoring() { ApplicationContext c ...