Creating an array by combining two arrays of objects

My task is to categorize products from the products array based on the corresponding season provided in the orders array. Each entry in the orders array contains a key-value pair for season (e.g., "season": "2015"). The products are associated with individual order objects using the "id" of the order array and the "orderlineId" of the products array.

Once I have grouped the products by season, they also need to be further grouped based on the values of "uniqueId" and "colorCode" found within product.uniqueId and product.colorCode.

Orders array

{
    "id": 99945333,
    "key": "1",
    "orderNumber": "01",
    "season": "2007"
},
{
    "id": 99945335,
    "key": "1",
    "orderNumber": "02",
    "season": "2016"
},
{
    "id": 99945333,
    "key": "2",
    "orderNumber": "03",
    "season": "2019"
},
{
    "id": 99945333,
    "key": "3",
    "orderNumber": "04",
    "season": "2017"
}
]

Products array

        "orderlineId": 99945333,
        "product": {
            "season": null,
            "size": "XXL",
            "category: "pants"
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80457",
            "year": null
        },
        "quantity": 1,
        "quantityDelivered": 0,
        "remark": null
    },
{
        "orderlineId": 99945333,
        "product": {
            "season": null,
            "size": "XXL",
            "category: "pants"
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80457",
            "year": null
        },
        "quantity": 1,
        "quantityDelivered": 0,
        "remark": null
    },
{
        "orderlineId": 99945335,
        "product": {
            "season": null,
            "size": "XXL",
            "category: "shirt"
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80457",
            "year": null
        },
        "quantity": 1,
        "quantityDelivered": 0,
        "remark": null
    },
{
        "orderlineId": 99945335,
        "product": {
            "season": null,
            "size": "XXL",
            "category: "trouser"
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80453",
            "year": null
        },
        "quantity": 1,
        "quantityDelivered": 0,
        "remark": null
    },
{
        "orderlineId": 99945473,
        "product": {
            "season": null,
            "category: "blouse"
            "size": "XXL",
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80453",
            "year": null
        },
        "quantity": 1,
        "quantityDelivered": 0,
        "remark": null
    },

I believe creating a new array would simplify the process for easier iteration.

Desired outcome: new array

      {
        "season": 2007,
        "products": [
           {
            "season": null,
            "size": "XXL",
            "category: "pants"
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80453",
            "year": null
           }
           { 
            "season": null,
            "size": "XXL",
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80453",
            "year": null
           }
        },
      {
        "season": 2016,
        "products": [
           {
            "season": null,
            "size": "XXL",
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80457",
            "year": null
           },
    },
           { 
            "season": null,
            "size": "XXL",
            "sizeSortCode": "60",
            "subSize": null,
            "subSizeSortCode": "0",
            "uniqueId": "80453",
            "year": null
           }
        }
]

This task has proven challenging. My initial plan is to iterate over the seasons first, but I am uncertain how to group the products and construct a new array. Any assistance would be greatly appreciated!

Answer №1

Oh,

After some exploration, I believe I have finally stumbled upon a satisfactory solution to my own inquiry. Although it may not align perfectly with the expected result, I am confident that I can make it work!. This is the technique I employed:

const combinedData = orders.concat(products).reduce((accumulated, current) => {
    accumulated[current.season] = Object.assign(accumulated[current.id] || {}, current);
    return accumulated;
}, {});
Object.keys(combinedData).map(index => combinedData[index]);

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

Graphing functions with three.js

Is it possible to create a function grapher using the three.js API to plot a function in the form of z=f(x,y)? The program should: Generate input values between -1 and 1 in increments of .1, and use these values to plot x, y, and z vertices as part of a ...

Is Vercel deploying an incorrect version?

After working on a project for a potential employer and fixing all errors, I deployed it using Vercel. However, upon deployment, the version that was sent to me was displayed instead of the completed one I see when running npm start locally. I would great ...

Issue with converting valid JSON to XML using XSLT 3.0 json-to-xml() function

The following JSON appears to be valid, but when attempting to transform it using XSLT 3.0's json-to-xml() function, an error related to the JSON syntax is encountered. { "identifier": { "use": "<div xmlns=\"http://www ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

Learn how to create a validation function for phone numbers in a React application that keeps the button disabled until a valid phone number

import React,{useState} from "react"; export default function ValidatePhone() { const [phoneNumber, setPhoneNumber] = useState(""); const [disableButton, setDisableButton] = useState(true); function handleChange(e) { setPho ...

Using the Spread Operator to modify a property within an array results in an object being returned instead of

I am trying to modify the property of an object similar to this, which is a simplified version with only a few properties: state = { pivotComuns: [ { id: 1, enabled : true }, { id: 2, enabled : true ...

Single array returned by observable

Issue: I am looking for a way to consolidate the multiple arrays returned individually into a single array. Solution: fetchAllRiders() { var distanceObs = Observable.create(observer => { this.http.get(this.API + '/driver/all').map(res = ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...

Guide to sending SweetAlert textarea input to an axios call

I need assistance in creating a simple pop-up form stepper using SweetAlert. The purpose is to allow users to input a report name, description, and comment, then send that data to the server for storage. My challenge lies in retrieving the value from the ...

Creating a dynamic textarea input based on the number entered using AngularJS

Can a loop be simplified in AngularJs to easily determine the number of textarea inputs a user can fill? <input type="number" class="form-control" min="1" max="4" value="1"> <div ng-repeat="..."> <div class="form-group"> < ...

Saving a dynamic form to the database and editing it later

I have developed a dynamic form builder using jQuery UI that allows users to drag form inputs anywhere on the screen and generate a report. Now, I am trying to figure out the best approach for saving this layout to a SQL database. How can I save the struct ...

The validity of the return statement in the ajax code is malfunctioning

Currently, I am in the process of validating duplicate email addresses from a database. Initially, I validate the email format, then check the email length and finally verify the email with the database using ajax. However, the return true or return false ...

What could be causing the issue of messages not displaying while incorporating connect-flash with res.locals in express.js and ejs templating?

Here are some snippets of code that may be useful. Connect-flash is designed to display messages on test1 and test2, but there seems to be an issue with displaying messages for test 3: user registration when all three tests are redirected to the same &apos ...

Invoke the prototype function through an onclick event after dynamically adding a button

Within my code, I have created two prototype functions named showPopup and buildView. The buildView function is responsible for generating dynamic HTML that includes a button. My intention is to invoke the showPopup function when this button is clicked. Ho ...

MVC - The challenge of users repeatedly clicking the Submit button

In my MVC application, there are multiple pages where users submit a form by clicking a Submit button. Occasionally, users may click the button multiple times if they don't see an immediate response, causing the form to be submitted twice. To address ...

A useful tip for emphasizing tags that have attributes with endings

Here is the HTML list I'm working with: <li class=​"info" data-info=​"" data-title=​"info 1" data-info-id=​"222643">…</li> <li class=​"info" data-info=​"" data-title=​"info 2" data-info-id=​"217145">…</li> ...

Semantic UI dropdown field not displaying selected option text

I've encountered an issue while working with React Semantic UI. I'm trying to render a dropdown and have configured it so that the selected option's text should display in the field. However, when I choose an option from the dropdown, instea ...

What is the significance of "new" being omitted in the upcoming jQuery script?

After diving into the JQuery documentation, I discovered that it is possible to create the event object like this: //Instantiate a new jQuery.Event object without using the "new" keyword. var e = jQuery.Event( "click" ); I find it puzzling why we don&apo ...

Is my approach to passing structures by reference incorrect?

#include<stdio.h> struct mystruct{ int age; //age of child int flag; //flag: if 1 then change the age, if 0 then don't }; /////////////////////////////////////////////////////////////////////////// ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...