Combining arrays of objects into one single array

I possess a large array of intricately nested objects, akin to this (imagine adding 76 more products for a clearer picture):

[
  {
    "ProductID": 11,
    "ProductName": "Queso Cabrales",
    "SupplierID": 5,
    "CategoryID": 4,
    "QuantityPerUnit": "1 kg pkg.",
    "UnitPrice": 21,
    "UnitsInStock": 22,
    "UnitsOnOrder": 30,
    "ReorderLevel": 30,
    "Discontinued": false,
    "orders": [
      {
        "OrderID": 10248,
        "CustomerID": "VINET",
        "EmployeeID": 5,
        "OrderDate": "1996-07-04T05:00:00.000Z",
        "RequiredDate": "1996-08-01T05:00:00.000Z",
        "ShippedDate": "1996-07-16T05:00:00.000Z",
        // More details here
      },
      {
        "OrderID": 10296,
        "CustomerID": "LILAS",
        "EmployeeID": 6,
        "OrderDate": "1996-09-03T05:00:00.000Z",
        "RequiredDate": "1996-10-01T05:00:00.000Z",
        "ShippedDate": "1996-09-11T05:00:00.000Z",
        // More details here
      } ... etc.

My task is to iterate through Orders and Order_Details and combine each Product's orders into a single array. Each product has multiple orders with a single order detail, so the desired output should resemble:

  {
        "ProductID": 11,
        "ProductName": "Queso Cabrales",
        // Other details merged from orders
}

The major challenges include:

  • Accessing order_details nested within each orderID.
  • Maintaining the association of one product to multiple orders (which almost broke the internet when I tried to merge everything into one huge array).

I aim to send this data to the client side for visualization using D3. Envision a stacked area chart with input data like:

var graph = {
    Spicy-Ramen: {[  
        [380.00, 12-March-2015], [420.62, 19-March-2015] 
    ]},
    Miso-Soup: {[
        [230.99, 12-April-2015], [322.60, 22-May-2015] 
    ]},
    Vegetable-Shumai: {[
        [22.99, 12-June-2015], [121.20, 29-August-2015]
    ]}
}

I attempted to use _.merge and _.assign without success - any assistance or guidance would be greatly appreciated.

Answer №1

If my understanding is correct, I would suggest creating separate objects for Products and Orders, where each key in the object corresponds to the element's id. For example, your Orders object could look something like this:

var Orders = {
    11:{"ProductID":11,"ProductName":...},
    12:{"ProductID":12,"ProductName":...},
}

This way, you can easily access order parameters by their respective ids.

You could apply a similar approach to order_details, although it may be beneficial to include its attributes within the Orders object as well.

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

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...

Tips for creating a mobile-friendly 30-day chart with chart.js

I created a chart displaying 30 days of absence data using the react-chartjs-2 library, but it is not responsive. How can I make it responsive? Here's how it appears on a laptop: chart on laptop And this is how it looks on mobile: chart on mobile T ...

Tips on incorporating a hyperlink into an object imported through GLTF loader

Is there a way to include a hyperlink in the object loaded using gltf loader with the given code snippet below? var loader = new THREE.GLTFLoader(); var mesh; loader.load('globe.glb', function(gltf){ console.log(gltf); me ...

Automating the process of running npm start on page load: A guide

Recently, I've been delving into learning npm in order to incorporate it into a website. I'm curious about how exactly it is used within a website - do you typically need to execute the command "npm start"? How does this integration work for a li ...

Tips for passing parameters to an ajax request in Django URL?

In my current setup, I'm passing a URL to the ajax like this: $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://loc ...

Having difficulty including a new key-value pair to a JSON object while using another JSON object

Looking to merge key value pairs from one JSON object into another. I've searched through various stackoverflow threads for solutions, but haven't found one that works for my specific scenario. const primaryObject = { name: "John Doe", ag ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

Can the issue of mangling be avoided during .NET minification?

Currently, I am utilizing the .NET Bundling and Minification feature to bundle and minify the files for my application. While this method works well, I am interested in exploring alternative solutions due to its complexity. Specifically, I am attempting t ...

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

Tips for navigating to an element with Nightwatch

I am currently using nightwatch for end-to-end testing of my application. One of the tests is failing because it seems unable to scroll to the element that needs to be tested. I am wondering if scrolling is necessary, or if there is another workaround. Her ...

Error in React Material UI: 'theme' variable is not defined - no-undef

In the process of developing a basic React application with material-ui, I am incorporating MuiThemeProvider and ThemeProvider for themes. App.js import React from 'react'; import { createMuiTheme, MuiThemeProvider } from '@material-ui/co ...

Ensure that the HTML input element only accepts positive values, including decimal numbers

I need to build an input field that only accepts positive numbers, including decimal values. Leading zeros are not allowed, and users should not be able to paste invalid values like -14.5 into the field. Here is my current implementation: <input type= ...

Tips for creating boxes with clearly defined edges on shared sides using three.js

When I draw boxes with common sides, I don't see the common edges, but rather perceive them as a single object even though there are 25 boxes: https://i.sstatic.net/gE8FW.png function box(scene, x, y, z, size) { const points = []; ...

Executing npm run build index.html results in a blank page being generated without any error messages or warnings

After building my react app with npm run build, I encountered a problem where clicking on index.html resulted in a blank page opening in the web browser. I explored several solutions to address this issue but none seemed to work. Some of the strategies I ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

An error occurred: an unexpected identifier was found when trying to import axios using './lib/axios.js' and require('axios')

I am currently working with a js file: test.js: const axios = require('axios'); console.log('test'); To set up the dependencies, I ran the command npm install This is how my folder structure is organized: test node_modules packa ...