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

Dealing with nested JSON structures in Python

I'm currently working on extracting data from a nested JSON structure using Python. Here's a brief example of the JSON data: { "daily" : { "1524182400000" : 438, "1524268800000" : 438, "1524355200000" : 437, ...

Unraveling complex nested classes in Java using Gson for deserialization

I am in need of transforming a JSON string tmp => {"result_count":1,"next_offset":1,"entry_list":[{"id":"xyz123","module_name":"Products","name_value_list":{"id":{"name":"id","value":"xyz123"},"name":{"name":"name","value":"test_product_2"}}}],"relationshi ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

Breaking the Boundaries of Fuzzy Search with JavaScript

I am currently utilizing ListJS's plugin for fuzzy search. It can be found at the following link: In an attempt to enhance the plugin, I implemented my own method to filter by the first letter of the items in the list. This involved selecting from an ...

Incorporate geographical data from a JSON file into my Google Maps application

Hey there, I'm a newbie on this forum and could really use your expertise. I've put together an html5 page with Google maps using the API key from Google (My code is shown below), it's working fine with a central marker in place and loads pe ...

`Testing the functionality of javascript/jQuery events using Jasmine`

I came across this code snippet: $(document).on('click', '#clear-button', clearCalculatedPrice) clearCalculatedPrice = -> $('#price_rule').removeAttr('data-original-title') $('#calculated-price&apos ...

Changing directions while the script is running

For my web site testing, I created a script using Tampermonkey that randomly browses the site and modifies parameters. Sometimes I need to navigate to a different page by either using window.location.replace(URL) or by clicking a button with the script l ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...

Issue: Headers cannot be set after they have been sent. This is a problem in node.js

I'm trying to create an application that allows users to execute commands via a URL, but I keep encountering this error message: _http_outgoing.js:346 throw new Error('Can\'t set headers after they are sent.'); ^Error: Can't ...

What is the process for incorporating a package.json file into a completed React application?

When using the npm build command to build a react app for production environment, we get a build folder containing html, css, and JavaScript files, but the package.json file is missing. If we try to use this file to set an http proxy endpoint for connecti ...

React.memo is failing to stop unnecessary re-renders of a stateless functional child component that does not receive any props

There is a stateless functional component known as Title, which utilizes React-Reveal to showcase simple heading elements upon rendering. Despite having no internal state and not receiving any props from its parent component (GameHeader), the issue arises ...

Changing a rest api POST request from JSON to form-data in Golang using the Gofiber framework

My current code successfully handles JSON in the body of a POST request, but I am now looking to switch to using form-data instead. This is my existing code: func Signin(c *fiber.Ctx) error { var data map[string]string if err := c.BodyParser(& ...

Choose2 incorporate on change

I have a Laravel project where I am using the vuexy theme. I've been trying to add an onchange event to my select2 input, but so far I haven't had any success. Here is my select2 input: <div class="col-12 mb-2"> <label class ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

problem with running a node server on localhost

I've been attempting to test a simple Javascript file, but I'm encountering difficulties. When I try to load the page in my browser, it seems to be stuck loading forever with no warnings. At the bottom of the page, a text bar appears stating "wai ...

What is the most effective way to retrieve data from a URL and process it using reactjs?

Looking to consume JSON data from a URL, here is an example of the JSON structure: { "results": [ ... ], "info": { ... } } I aim to display the fetched data as a component property. What is the most efficient way to achie ...

Just a quick inquiry regarding adding new line characters in JSON to be used in

After encountering an issue with a JSON file in my JavaScript application where it would not print new lines when viewed on the console, I am at a loss for a solution. The contents of my JSON file are as follows: [ { "id": "71046" ...

Filtering a list with Vue.js using an array of checkboxes

Currently, I am exploring ways to filter a v-for list using a checkbox model array with multiple checkboxes selected. Most examples I have come across only demonstrate filtering one checkbox at a time. In the demo here, you can see checkboxes 1-3 and a lis ...

Use ajax to load the script

Encountering a puzzling issue with a script loading function on my IIS local web server. function loadJs(scriptName) { var name = scriptName.toString(); var myUrl = 'http://192.168.1.149/7.0.9.5/m/js/'; myUrl += name; debugger; ...