Adding an array to the attribute of a different array in JavaScript

I'm currently navigating my way through learning Javascript and have hit a roadblock with the merging of two arrays of objects based on an ID. Although I am able to merge the two arrays, the resulting output is not as anticipated.

Here are the two object arrays in question:

"product": [
        {
            "id": "1000",
            "code": "f230fh0g3",
            "name": "Bamboo Watch",
            "description": "Product Description",
            "image": "bamboo-watch.jpg",
            "price": 65,
            "category": "Accessories",
            "quantity": 24,
         }
]

"orders": [            
       {                
            "id": "1000",             
            "productID": "f230fh0g3",           
            "date": "2020-09-13",
            "amount": 65,
            "quantity": 1,
       },
       {                
            "id": "1000",             
            "productID": "f230fh0g3",           
            "date": "2020-09-13",
            "amount": 65,
            "quantity": 1,
       },
]

My aim is to merge both arrays based on a common key (id) to create a unified array structured like this:

"product": [
        {
            "id": "1000",
            "code": "f230fh0g3",
            "name": "Bamboo Watch",
            "description": "Product Description",
            "image": "bamboo-watch.jpg",
            "price": 65,
            "category": "Accessories",
            "quantity": 24,
            "orders": [
                {
                    "id": "1000",
                    "productCode": "f230fh0g3",
                    "date": "2020-09-13",
                    "amount": 65,
                    "quantity": 1,
                    "customer": "David James",
                    "status": "PENDING"
                },
                {
                    "id": "1001",
                    "productCode": "f230fh0g3",
                    "date": "2020-05-14",
                    "amount": 130,
                    "quantity": 2,
                    "customer": "Leon Rodrigues",
                    "status": "DELIVERED"
                },
              ]
    },
    {
         "id": "1001",
         "..."
         "orders": [
               {
                     "id" "1001",
                     "..."
               }
           ]
    }]

Is it feasible to map out these arrays in such a manner? Thank you for your assistance.

Answer №1

Achieving this task is indeed possible. By utilizing both the .map() and .filter() functions simultaneously, you can accomplish your desired outcome. If you have a list of products stored in the product variable and a set of orders stored in the order variable, you can merge these two lists as follows:

const result = products.map(
    product => ({
        ...product,
        orders: orders.filter(
            ({ productID }) => productID === product.id
        )
    })
);

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

Issue with local dependency not being loaded until after a hard refresh in Vue/Vue Router

I'm currently developing a Vue application that utilizes Vue router. I've been attempting to integrate the jscolor script found at here. Essentially, you just need to include the script and apply the jscolor class to an HTML element. I am working ...

Vue-Cookies Having Trouble Retrieving Cookies

I'm currently setting up an OAuth service between my Node.js back-end and Vue front-end. Right now, the back-end is functioning correctly; I can authenticate successfully with my google account and get redirected to the appropriate UI view after authe ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

AngularJS enhanced dropdown navigation bar built using Bootstrap styling

I'm currently learning how to implement Bootstrap, but I've run into an issue. I created a dropdown in the navigation bar, but when I clicked on it, the dropdown didn't collapse as expected. The class="dropdown" didn't change to class= ...

What could be the reason for the failure of @babel/preset-react automatic transformation with Webpack?

The setup involves a Yarn monorepo with a babel.config.js that specifies the environment. React version being used is 18.1.x. I have a similar configuration that works perfectly fine in another setup, but it's failing here. I've been painstaking ...

How to enable Autocomplete popper to expand beyond the menu boundaries in Material UI

Within my Menu component, I have an Autocomplete element. When the Autocomplete is clicked, the dropdown list/Popper appears but it's confined within the Menu parent. How can I make it so that the Autocomplete's dropdown list/Popper isn't re ...

Take a custom action once all elements have been rendered with ng-repeat

Looking to manipulate a DIV element generated by ng-repeat: <div ng-repeat="data in info" > <div id='plot_{{data.id}}'></div> </div> Here is the sequence of events: Information added to $scope.info ng-repeat exec ...

I am attempting to generate a displacement map effect to smoothly transition between three images using the ThreeJs library, but I have hit a roadblock

My journey with ThreeJS started a few months back, leading me into the fascinating world of webgl. I delved into numerous courses on YouTube, but most of them were centered around 3D compositions. While I have developed a basic understanding of how things ...

fullpage.js: the content exceeds the height limit

I am currently working on customizing the jquery script fullpage.js for a website built on the French CMS "SPIP" (). This script is used to create a one-page website with both horizontal and vertical navigation. However, I have encountered an issue with ...

Steps to eliminate pre-chosen alternatives upon loading select control?

When using react-select with pre-selected options and multiple select enabled, the issue arises where clicking on the Select box still displays the already pre-selected options. How can I remove these duplicate options from the list? Below is a snippet of ...

Is there a way to customize the appearance of an MUI checkbox that was not created by me?

I'm utilizing Material-Table for data display and making use of the columnsButton property in table options to enable column hiding. I want to customize the checkboxes that show up to match my color scheme. When the columnsButton property is set, a s ...

After making an AJAX call, the table data can be found in page 1 under the tbody

Can anyone help me with this issue? I've gone through all the guides related to this problem and followed them step by step, but still no success. After populating the table using an AJAX call, all the data appears on a single page only. I attempted ...

The fadeOut method does not support the removeClass function

I've encountered a small issue while trying to create a slider with images. As someone who is new to javascript and jquery, I attempted to build it based on my past experience with Codeacademy. However, the code that used to work fine there is now cau ...

Selecting all the li elements inside a ul with a jQuery selector

When creating a menu, I want to apply the .active class only to child elements when clicked on li children, not the parent li. (Utilizing the enfold WordPress theme) $('#mobile-advanced li.menu-item-has-children').on('click', functi ...

Changing PHP string into a JavaScript array for use in Google Charts

Attempting to construct a Google Sankey Chart using data fetched from a MySQL database. Once the page has loaded, an ajax call is initiated to retrieve the data from MySQL and present it on the view. This is how the data is being returned from PHP: echo ...

Error in AngularX TS: Trying to invoke a type that does not have a callable signature

Encountering an issue while working on a component, specifically during ng serve/build process. Please note that this error is different from any console errors, despite what some may think. The expected outcome is for the code to successfully build and ru ...

Node Pagination and Filtering feature malfunctioning

I am currently working on incorporating Pagination and Filtering in the backend functionality. This controller receives input such as Page number and Filtering conditions. Controller:- const getPosts = asyncHandler(async (req, res) => { const { ...

Error: Cannot locate the named export 'remove' in Apollo Client

As I work on developing an apollo client plugin for a Nuxt 3 application, I encountered an error related to a package named ts-invariant: file:///Users/[my name]/Repositories/[project]/node_modules/@apollo/client/utilities/globals/fix-graphql.js:1 import { ...

Why does Next.js throw an error when using an additional <div></div>?

I'm new to exploring Next.js and I'm encountering an error when using the html tag twice. It works fine with just one container, but as soon as I add another one, this error pops up: Error: error: Unexpected token "div". Expected jsx i ...

`When utilizing $routeParams, the CSS fails to load`

Whenever I use parameters in ngRoute and go directly to the URL (without clicking a link on the site), the CSS fails to load. All my routes are functioning properly except for /chef/:id. I utilized yeoman's angular generator, and I am running everythi ...