Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements.

 [{
            containerId: 'c12',
            containerNumber: '4321dkjkfdj',
            goods: [{
                weight: '32kg',
                quantity: '3'
            }]
        },
     { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{
            weight: '322kg',
            quantity: '32'
        }]
    },
    
    {
        containerId: 'c13',
        containerNumber: '1212dkjkfdj',
        goods: [{
            weight: '13kg',
            quantity: '3'
        }]
    },
     {containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{
    weight: '13kg',
    quantity: '3'
    }]
    },

]

I need to consolidate objects with the same 'containerId' into one object, including all 'goods' under that 'containerId' as shown in the code below:

    [{
        containerId: 'c12',
        containerNumber: '4321dkjkfdj',
        goods: [{
                weight: '32kg',
                quantity: '3'
            },
            {
                weight: '322kg',
                quantity: '32'
            }
        ]

    },
    {
        containerId: 'c13',
        containerNumber: '1212dkjkfdj',
        goods: [{
                weight: '13kg',
                quantity: '3'
            },
            {
                weight: '13kg',
                quantity: '3'
            }
        ]
    }
]

Answer №1

To create a lookup object, iterate through the items and utilize .reduce(). The key in this case will be containerId, with corresponding values as

{containerId, containerNumber, goods}
. If the key is already present in the accumulator as a[containerId], simply update the goods value.

const arr = [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '32kg', quantity: '3' }] }, { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '322kg', quantity: '32' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] } ]

const res = arr.reduce((a,{containerId, containerNumber, goods}) => ((a[containerId] ??= {containerId, containerNumber, goods: []}).goods = [...a[containerId].goods, ...goods],a), {});
console.log(Object.values(res));
.as-console-wrapper { max-height: 100% !important }

Answer №2

const shipments = [
    {
        containerId: 'c12',
        containerNumber: '4321dkjkfdj',
        goods: [{
            weight: '32kg',
            quantity: '3'
        }]
    },
    {
        containerId: 'c12',
        containerNumber: '4321dkjkfdj',
        goods: [{
            weight: '322kg',
            quantity: '32'
        }]
    },
    {
        containerId: 'c13',
        containerNumber: '1212dkjkfdj',
        goods: [{
            weight: '13kg',
            quantity: '3'
        }]
    },
    {
        containerId: 'c13',
        containerNumber: '1212dkjkfdj',
        goods: [{
            weight: '13kg',
            quantity: '3'
        }]
    }
]

const uniqueShipments = shipments.reduce((previous, current) => {
    const foundIndex = previous.findIndex(prev => prev.containerId === current.containerId);
    
    if (foundIndex === -1) {
        previous.push(current);
    } else {
        previous[foundIndex].goods.push(current.goods);
    }
    
    return previous;
}, []);

console.log(uniqueShipments);

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

What could be causing the mysql-event to not function properly in a Node.js environment?

const MySQLEvents = require('mysql-events'); const databaseInfo = { host: 'localhost', user: 'root', password: '' //blank password }; const mysqlEventWatcher = MySQLEvents(databaseInfo); console.log(mys ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

Clicking on the image in an owl carousel slider does not trigger the onsen template page to load

I am experiencing an issue with my owl carousel slider while calling an API for page content on image click. I have implemented an onsen template page using ng-click on image, but it only works for the first image click. Subsequent images do not call the o ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

Unveiling the mystery of extracting information from a string post serialization

When working with a form, I am using this jQuery code to fetch all the field values: var adtitletoshow = $("#form_data").serialize(); After alerting adtitletoshow, it displays something like this - &fomdata1=textone&fomdata2=texttwo&fomdat ...

How can I create a custom checkbox in React Bootstrap without specifying an ID

I'm struggling to understand why this seemingly straightforward Bootstrap custom checkbox isn't functioning as expected. My project involves React, Bootstrap, and React-Bootstrap. import React from "react"; import ReactDOM from "react-dom"; impo ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

Setting up package.json to relocate node_modules to a different directory outside of the web application:

My web app is currently located in C:\Google-drive\vue-app. When I run the command yarn build, it installs a node_modules folder within C:\Google-drive\vue-app. However, since I am using Google Drive to sync my web app source code to Go ...

JavaScript for switching between grid layouts

I have organized 3 DIVs using a grid layout. There is a Navigation bar with an on-click event attached to it. When a button on the nav-bar is clicked, I want the JavaScript function to display the corresponding grid associated with that button. Currently, ...

Top method for saving information on page for Ajax calls

On my dynamically generated page, there is an array of data produced by php that I want to utilize for an ajax request. However, I am unsure of the best method to store this data on the page as it is not sensitive and does not involve a form. Currently, I ...

Exploring the fusion of different interfaces and props in React using typescript

I have designed an interface as shown below, representing the "base button". export interface ButtonProps { backgroundColor?: Colors, children?: React.ReactNode | JSX.Element, style?: CSSProperties, disabled?: boolean, onClick?: () => ...

Can you tell me the method of checking the number of members in a voice channel?

Is there a method to determine the number of members in a voice channel or check if it's empty using discord.js (V. 13.8.1)? I attempted the following code: async function countMembers(voiceState){ let users = await voiceState.channel.members.siz ...

How to position an absolute element beneath a fixed element

My website is experiencing a problem where the fixed header is overlapping an absolute paragraph on this page. Does anyone know how to resolve this issue? ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Styled-components causing issues with conditional rendering

Within my React component, I have multiple properties and I want styles to only apply if a property has a value. I attempted the following code: export const Text = ({text, color, size, fontFamily}) => { const StyledParagraph = styled.p` m ...

Communication between AngularJS directives and controllers occur when a function is called upon a change

I have developed a unique custom directive which is defined as: <div class="col-md-6"> {{templateMapping[colProp].SheetPointer}} <select class="form-control" ng-model="selectedColumn" ng-change="changeMapping()" ng ...

The function of AJAX is to send and receive data asynchronously without

Recently, I was experimenting with AJAX. When I use echo "hello" in my PHP file, everything works perfectly. However, if I try something like echo "<script language=Javascript> alert('hi');</script>"; in the PHP file, the alert ...

Sometimes the function setFromObject(mesh) returns inaccurate values

THREE.Box3.setFromObject(*object*) is returning inaccurate values. I will demonstrate my process in understanding this issue: I am creating 2 meshes using vertices. The first one using the triangle() function, and the other using trapezoidForm(). var tri ...

Error: The validation process failed due to missing information. The file name and path are both required for validation

In my current project, I am attempting to upload a file from the frontend to the backend and save it. However, I am encountering an error that looks like this: Error The error message is as follows: this.$__.validationError = new ValidationError(th ...

Error: Attempted to bootstrap Angular multiple times

While developing an app using angularjs, everything functions correctly after loading a web page. However, a message appears on the console saying: WARNING: Tried to load angular more than once. Upon checking the angular.js file, I found this code snippe ...