What is the best way to merge JSON objects with identical keys and sum their respective values together?

I attempted the code snippet below.

var SeatWithCat = [{
  "level": "Level II",
  "price": 5,
  "quantity": 1,
  "seats": "B3"
}, {
  "level": "Level II",
  "price": 5,
  "quantity": 1,
  "seats": "B1"
}, {
  "level": "Level I",
  "price": 10,
  "quantity": 1,
  "seats": "A2"
}, {
  "level": "Level III",
  "price": 30,
  "quantity": 1,
  "seats": "C1"
}, {
  "level": "Level III",
  "price": 30,
  "quantity": 1,
  "seats": "C2"
}, {
  "level": "Level V",
  "price": 50,
  "quantity": 1,
  "seats": "E1"
}, {
  "level": "Level II",
  "price": 5,
  "quantity": 1,
  "seats": "B2"
}, {
  "level": "Level VI",
  "price": 2,
  "quantity": 1,
  "seats": "F1"
}];
var temp = [];
var jsonarr = [];
for (var i = 0; i < SeatWithCat.length; i++) {
  for (var j = 1; j < SeatWithCat.length; j++) {
    if (SeatWithCat[i].level === SeatWithCat[j].level) {
      temp.push({
        level: SeatWithCat[i].level,
        quantity: SeatWithCat[i].quantity + SeatWithCat[j].quantity,
        price: SeatWithCat[i].price + SeatWithCat[j].price,
        seats: SeatWithCat[i].seats + "," + SeatWithCat[j].seats
      });
      SeatWithCat = SeatWithCat.filter(function(el) {
        return el.level !== SeatWithCat[i].level;
      });
      jsonarr = SeatWithCat;
      alert(JSON.stringify(temp));
    }
  }
}
var finalObj = temp.concat(jsonarr);
alert(JSON.stringify(finalObj));

Results:

[{
  "level": "Level II",
  "quantity": 2,
  "price": 10,
  "seats": "B3,B1"
}, {
  "level": "Level III",
  "quantity": 2,
  "price": 60,
  "seats": "C1,C1"
}, {
  "level": "Level VI",
  "quantity": 2,
  "price": 4,
  "seats": "F1,F1"
}, {
  "level": "Level I",
  "price": 10,
  "quantity": 1,
  "seats": "A2"
}, {
  "level": "Level V",
  "price": 50,
  "quantity": 1,
  "seats": "E1"
}]

The existing solution works fine when only two objects share the same level. However, it fails to calculate correctly when more than two objects in the array have the same level. My goal is to account for any number of objects with matching levels. Appreciate your help!

Answer №1

To gather distinctive elements in a dictionary, you can utilize Array.prototype.reduce(), and then convert the dictionary back into an array by using Array.prototype.map():

function merge(arr) {
  var merged = arr.reduce(function(output, element) {
    var current = output[element.level];

    output[element.level] = !current ? element : {
      level: element.level,
      price: current.price + element.price,
      quantity: current.quantity + element.quantity,
      seats: current.seats + ',' + element.seats
    };

    return output;
  }, {});

  return Object.keys(merged).map(function(key) {
    return merged[key];
  });
}

var SeatWithCat = [{"level":"Level II","price":5,"quantity":1,"seats":"B3"},{"level":"Level II","price":5,"quantity":1,"seats":"B1"},{"level":"Level I","price":10,"quantity":1,"seats":"A2"},{"level":"Level III","price":30,"quantity":1,"seats":"C1"},{"level":"Level III","price":30,"quantity":1,"seats":"C2"},{"level":"Level V","price":50,"quantity":1,"seats":"E1"},{"level":"Level II","price":5,"quantity":1,"seats":"B2"},{"level":"Level VI","price":2,"quantity":1,"seats":"F1"}];

var outcome = merge(SeatWithCat);

console.log(outcome);

Answer №2

A hash table can be utilized as a reference to the corresponding object at the same level within the result set.

To implement this, iterate through the array and verify the existence of a hash - if not present, create a new object with the specified properties. If the hash already exists, update the quantity and append the seats.

This approach streamlines the process by utilizing only one loop.

var seatWithCat = [{ level: "Level II", price: 5, quantity: 1, seats: "B3" }, { level: "Level II", price: 5, quantity: 1, seats: "B1" }, { level: "Level I", price: 10, quantity: 1, seats: "A2" }, { level: "Level III", price: 30, quantity: 1, seats: "C1" }, { level: "Level III", price: 30, quantity: 1, seats: "C2" }, { level: "Level V", price: 50, quantity: 1, seats: "E1" }, { level: "Level II", price: 5, quantity: 1, seats: "B2" }, { level: "Level VI", price: 2, quantity: 1, seats: "F1" }],
    result = [];

seatWithCat.forEach(function (o) {
    if (!this[o.level]) {
        this[o.level] = { level: o.level, price: o.price, quantity: o.quantity, seats: o.seats };
        result.push(this[o.level]);
        return;
    }
    this[o.level].quantity += o.quantity;
    this[o.level].seats += ',' + o.seats;
}, Object.create(null));

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

JQuery Slider's Hidden Feature: Functioning Perfectly Despite Being Invisible

Having an issue with a jQuery slider on my local HTML page. The sliders are not showing up as intended. I want it to display like this example: http://jsfiddle.net/RwfFH/143/ HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

Use VueJS v-on:click and Vanilla JS to collapse various divs when clicked

Can VueJS and vanilla JS be used to collapse specific divs among many? I have information contained in separate card elements that include a title and a body. My goal is to make the body of each card expand or collapse when the respective title is clicked ...

Embedding Facebook data into an HTML document

While I am able to retrieve data from Facebook and display it on the console, I am facing issues when trying to display it on an HTML page. I attempted using: $("#mydiv").text(data); or $("#mydiv").append(data); However, this displays [object Object] ...

What is the best way to showcase the chosen items from a treeview in ReactJS?

I'm struggling to figure out how to showcase the selected elements from my treeview. Any ideas or tips? The main purpose of this treeview is to filter data for export purposes. You can find the original code here. import React, {useEffect, useState} ...

Kendo Grid custom pop-up editor template featuring a unique jQuery Accordion Wizard

I am encountering an issue with executing the jQuery code inside the Kendo Grid Editor popup. I have attempted to incorporate this feature: While I can successfully display the accordion within the edit window popup, the functionality is not working as e ...

Looking for an angular split pane library that is built exclusively for AngularJS without any reliance on other frameworks?

Is there a split-pane library available that can enable me to display 2 tables on a screen and allow users to drag the divider in the middle to adjust the sizes of each table? I have come across libraries such as the shagstrom one that offer this function ...

Encountering PHP error when trying to access input type=file using jQuery/AJAX technique

I'm trying to use jQuery/AJAX to access the input type=file and pass the file value to a PHP page. However, I keep getting the following error message: Notice: Undefined index: file in D:\software installed\xampp\htdocs\contact-ma ...

What is the best way to locate every object based on its ID?

Currently, I am facing an issue where I have a list of IDs and I need to search for the corresponding object in the database. My tech stack includes Nodejs, Typescript, TypeORM, and Postgres as the database. The IDs that I am working with are UUIDs. ...

Is There a Lack of 'Contains' Support in JavaScript's ScriptEngine?

Below is some code that I am working with. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("[1, 2, 3].contains(1)"); However, when I run the code, it throws the following e ...

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

What is the best way to prevent a jQuery hover event from adding a text-shadow to the CSS?

Currently, I am facing an issue with a jQuery event that triggers a text-shadow effect: $(".leftColumn").hover(function (){ $(".leftColumn h2").css("text-shadow", "0px 2px 3px rgba(0, 0, 0, 0.5)"); },function(){}); The problem arises when the text-shad ...

Silent failure of product image upload in Java with Magento2 REST API leads to unexpected outcomes

Recently, I set up a Magento CE 2.1.2 online store. My main goal now is to utilize Java for uploading products to my store through the Magento REST API. After successfully configuring 2 leg OAuth using Apache-commons-httpclient and ensuring seamless produc ...

Extract string array from JSON data

Here is the JSON object I have: {"error":null, "result":[{"id":"1234567890", "count":1, "recipients": ["u3848", "u8958", "u7477474" ], "dateCreated":"2012-06-13T09: ...

Is the JSON Response Invalid?

I'm facing a peculiar issue with my page that processes some data and returns a JSON response. The problem arises when I make a jQuery Ajax call to this page, as Firefox shows an Invalid JSON error during inspection. Below is the code snippet of the ...

Serialize an object or an array using the DataContractJsonSerializer

Currently, I am utilizing the tomtom json api. This api has the capability to return either an array of objects or a single object in the event of an error. For example: [{"driverno": "... Error Example: {"errorCode": "8011","errorMsg": "request quota ...

Tips on expanding the dimensions and incorporating more members in a radar graph's Chartjs tag

I need to make some adjustments to the font size and color in a radar chart. Specifically, I want to change the name on the side of each data point. I have already tried adjusting the legend labels using the following code: options={{ ...

What causes the `global.require` function to return undefined when running as a nodejs script?

When piping a script to node and logging global.require, it appears as a function. However, when running the script passed to node directly, it is undefined... ➜ Desktop cat req.js console.log(global.require) ➜ Desktop cat req.js | node { [Functi ...

verified firebase/firestore requests

I've been struggling with the process of sending authenticated firebase/firestore calls. I set up firestore in my web app using Next.js as shown below: import { initializeApp } from "firebase/app"; import { getFirestore } from 'firebase ...

Problem with particles.js overlap due to dimensions of the canvas

Kindly refrain from marking this as a duplicate or invalid! I am currently working on a project where I am trying to incorporate particle.js into a Bootstrap template. Following the body tag, I placed the particle-js div and then created a container insid ...

Leverage angular-translate to establish placeholder text upon blurring

Just starting out with Angular and facing the challenge of implementing localization in my project. I have a lot of input fields that need their placeholders translated. In my HTML, I'm trying to achieve this: <input type="email" placeholder="{{ & ...