Merge an object depending on the matching criteria

Welcome fellow programmers and like-minded individuals,

Every time a user clicks on a basket to add a product, an object named field_x is created, where x increments by 1 starting from 1.

My objective is to develop a function that can identify duplicate items, merge their piece values, update the first item with this new total, and remove any other matching arrays.

Here is an example of what I aim to achieve in string format:

Input:

  • field_1 [{"name":"A","piece":1,"active":"true"}]

  • field_2 [{"name":"B","piece":1,"active":"true"}]

  • field_3 [{"name":"A","piece":1,"active":"true"}]

  • field_4 [{"name":"C","piece":1,"active":"true"}]

  • field_5 [{"name":"A","piece":1,"active":"true"}]

  • field_6 [{"name":"A","piece":1,"active":"true"}]

  • field_7 [{"name":"B","piece":1,"active":"true"}]

  • field_8 [{"name":"C","piece":1,"active":"true"}]

  • field_9 [{"name":"A","piece":1,"active":"true"}]

  • field_10 [{"name":"A","piece":1,"active":"true"}]

Output:

  • field_1 [{"name":"A","piece":6,"active":"true"}]

  • field_2 [{"name":"B","piece":2,"active":"true"}]

  • field_3 [{"name":"C","piece":2,"active":"true"}]

I want to emphasize that I do not plan to use eval in the final version as it is not considered best practice. I have alternative methods to replace it.

The current code I have does not offer me a solution, and I am unsure about the next steps to take.

<script src="js/underscore.js"></script>

<script>
var fieldsNumber = 10;

var field_1 = new Array();
var field_2 = new Array();

var field_3 = new Array();
var field_4 = new Array();

var field_5 = new Array();
var field_6 = new Array();

var field_7 = new Array();
var field_8 = new Array();

var field_9 = new Array();
var field_10 = new Array();

// Rest of the JavaScript code...

Any suggestions or feedback are welcomed!

Answer №1

To improve the organization of parts collection, I recommend utilizing a more structured approach within an array. This allows for easier iteration over the array using Array#forEach to group the parts efficiently.

var data = [{ name: "A", piece: 1, active: "true" }, { name: "B", piece: 1, active: "true" }, { name: "A", piece: 1, active: "true" }, { name: "C", piece: 1, active: "true" }, { name: "A", piece: 1, active: "true" }, { name: "A", piece: 1, active: "true" }, { name: "B", piece: 1, active: "true" }, { name: "C", piece: 1, active: "true" }, { name: "A", piece: 1, active: "true" }, { name: "A", piece: 1, active: "true" }],
    grouped = [];

data.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name, piece: 0, active: a.active };
        grouped.push(this[a.name]);
    }
    this[a.name].piece += a.piece;
}, Object.create(null));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

For an even more optimized structure, consider employing an object with names as keys for quick access to item counts and other relevant data:

var items = {
    A: {
        name: "A",
        piece: 1,
        active: "true"
    },
    B: {
        name: "B",
        piece: 1,
        active: "true"
    },
    C: {
        name: "C",
        piece: 1,
        active: "true"
    }
};

Additionally, you can enhance key creation by incorporating multiple parameters:

var dataToProcess = [{ "row": 4, "col": 3, "kg_m": "1.36", "m_t": "735", "v_d": 5000, "selectedTransection": "rectangle", "dCellText": "30x20", "mmCellText": "2", "active": "true", "piece": 1 }, { "row": 4, "col": 3, "kg_m": "1.36", "m_t": "735", "v_d": 6000, "selectedTransection": "rectangle", "dCellText": "30x20", "mmCellText": "2", "active": "true", "piece": 1 }, { "row": 4, "col": 3, "kg_m": "1.92", "m_t": "521", "v_d": 5000, "selectedTransection": "circle", "dCellText": "33.7", "mmCellText": "2.5", "active": "true", "piece": 1 }, { "row": 5, "col": 1, "kg_m": "1.78", "m_t": "562", "v_d": 6000, "selectedTransection": "circle", "dCellText": "38", "mmCellText": "2", "active": "true", "piece": 20 }, { "row": 5, "col": 1, "kg_m": "1.78", "m_t": "562", "v_d": 6000, "selectedTransection": "circle", "dCellText": "38", "mmCellText": "2", "active": "true", "piece": 1 }], 
    dataProcessed = [];
    
dataToProcess.forEach(function (a) {
    var key = [a.name, a.col, a.kg_m, a.m_t, a.v_d, a.selectedTransection, a.dCellText, a.mmCellText].join('|');
    if (!this[key]) {
        this[key] = {
            row: a.row,
            col: a.col,
            kg_m: a.kg_m,
            m_t: a.m_t,
            v_d: a.v_d,
            selectedTransection: a.selectedTransection,
            dCellText: a.dCellText,
            mmCellText: a.mmCellText,
            active: a.active,
            piece: 0
        };
        dataProcessed.push(this[key]);
    }
    this[key].piece += a.piece;
}, Object.create(null));

console.log(dataProcessed);
.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

How can I retrieve the results of an SQLite call in HTML5 without passing them to a separate function?

How can I use SQLite in HTML5 to execute a call like the one below, so that the result is returned immediately rather than passed off to another function? try { mydb.transaction( function(transaction) { transaction.executeSql( &apo ...

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

Form validation using JQuery within a Bootstrap 4 modal incorporating tabs is preventing submission

Encountering a challenge with JQuery Validation within a modal that contains tabs. When I'm on the Sign-in Tab and click the Login button, the validation errors display correctly: https://i.sstatic.net/caReK.jpg ISSUE 1 However, on the New Account ...

Elements that are added dynamically do not contain any space between each other

I have a markup template that looks like this. <template id="unsequenced-template"> <button type="button" class="btn btn-primary railcar"></button> </template> Then, I use the following JavaScript ...

Send two field values via axios by utilizing a b-form-select component from the Bootstrap Vue library

I'm struggling to send two fields to my backend, but every time I attempt to do so, both values end up as null in the backend. I am uncertain about what mistake I might be making. <template> <div id="app"> <div> ...

What is the best way to transfer data between functions prior to serializing and submitting the form?

Here are two functions I am working with: $("#form_pdetail").on("click", "#register_button", function() { var detail_add = $("#form_pdetail").serialize(); var request = $.ajax({ type: 'POST', url: "{{ path('product_d ...

Angular 4/5 | Custom Dropdown Component

I have been working on a custom dropdown directive in Angular that I can attach to any DOM element. Below is the code for my directive: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appDropdown]' ...

To search for specific data in a Mongoose schema by specifying an attribute of type ObjectId

Here are the schemas I am working with: UserLike const UserLikeSchema = Schema({ user: { type: Schema.Types.ObjectId, ref: "User", required: [true, "User is required"], }, game: { type: Schema.Types.ObjectId, ...

How can one locate the Unicode values for subscript letters in the alphabet?

While I have uncovered a few letters, my search continues for the elusive "c", "m", and "p". Is it possible to locate them as well? ...

What is the best way to transfer information from a model to the screen?

I need assistance with adding a Todo using a model. When I click the Add todo button located at the bottom of the page, it opens the model. I want to be able to add whatever I type in the input field to the list. How can I send the input field data to the ...

Arranging the columns of a matrix

My dilemma involves a matrix (or multidimensional array) filled with non-unique values, similar to this example: var matrix = [ [1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4] ] I am in need ...

What is the best way to update the color of a v-select component?

https://i.sstatic.net/6VOIo.png Currently utilizing Vuetify for my project <v-select id="makeMeBlue" dense outlined :items="form.values.urlTypes" label="Single or Multi URL" v-model="form.values.urlType" ...

Guide to refreshing a localStorage variable before transferring it to an Ajax request

I have a scenario where I need to update the localStorage value when an option is clicked from a list. The data-id value of the clicked option should be stored in localStorage and then sent through an Ajax call. However, the issue I am facing is that the l ...

Having trouble exporting data from Excel using react-data-export

I've been attempting to create an excel export feature, but for some unknown reason, it's not functioning properly. I'm utilizing react-data-export and followed a small test example from this GitHub link, yet the export is not working as exp ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Create a personalized attribute for division automation

Is it possible to automatically divide a dynamically populated ListView in jQuery-mobile into two groups based on the attribute values (Downloaded/Not downloaded)? Some listitems have the attribute status="true" while others have status="false". Here is t ...

Ways to pass a message from index.html to a Vue.js 3 instance

Picture this scenario: You have a Vue index.html file that also loads a custom script: <!DOCTYPE html> <html lang="en"> <head> ... ... <script type="text/javascript"> languagePluginLoader.then(fun ...

What is the syntax for creating an array in a Sails model?

I have encountered a problem that requires a model similar to an array. Here is my current model: module.exports = { attributes: { foodname:{ type: 'string', unique: true, required: true, }, foodreview:'strin ...

The attempt to run 'setProperty' on 'CSSStyleDeclaration' was unsuccessful as these styles are precalculated, rendering the 'opacity' property unchangeable

I am attempting to change the value of a property in my pseudo element CSS class using a JavaScript file. Unfortunately, I keep encountering the error mentioned in the title. Is there any other method that can be used to achieve this? CSS Code: .list { ...

Firefox is unable to display SWF files

My code snippet: <div id="sw" style="cursor:pointer" > <object id="swfobj" type="application/x-shockwave-flash"> </object> The JavaScript part: function openfile(filePath) { $("#swfobj").attr("data", filePath); $("#sw ...