Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below:

Consider this scenario:

objA = { 
    data: {
        SH: { propertyA: 0, propertyB: 3, propertyC: 0},
        ....
    }
}
objB = { 
    data: {
        SH: { propertyA: 0, propertyB: 0, propertyC: 1},
        ....
    }
}
objC = { 
    data: {
        SH: { propertyA: 4, propertyB: 0, propertyC: 0},
        ....
    }
}

The desired outcome should look like this:

objC = { 
    data: {
        SH: { propertyA: 4, propertyB: 3, propertyC: 1},
        ...
    } 
}

Is it feasible to perform such additions?

If not, could you propose an alternative coding method that does not involve maintaining three separate object types for each?

EDIT: When mentioning addition, I am referring to adding numerical values of properties from the three objects. While some properties may be strings, my focus lies only on numerical values.

Answer №1

Ultimately, it involves a significant amount of looping. There are various ways to approach the looping process. One simple method is to examine the objects themselves and include new elements when they are missing.

objD = { 
    data: {
        SH: { propertyA: 0, propertyB: 3, propertyC: 0, x: 'funky-chicken'},
        OP: { OO: 1, ZZ: 2 },
    }
}
objE = { 
    data: {
        SH: { propertyA: 0, propertyB: 0, propertyC: 1, x: 'funky-chicken'},
        OP: { OO: 1, YY: 100 },
    }
}
objF = { 
    data: {
        SH: { propertyA: 4, propertyB: 0, propertyC: 0},
        AA: { A: 1 },
    }
}

const finalResult = [objD, objE, objF].reduce(({ data }, obj) => {
  const objectEntries = Object.entries(obj.data);
  objectEntries.forEach(([key, items]) => {
    if (!data[key]){
      data[key] = { ...items };
    } else {
      Object.entries(items).forEach(([item, value]) => {
        if(typeof value === 'number') {
          data[key][item] = ( data[key][item] || 0 ) + value;
        }
      });
    }
  });
  return { data };
}, { data: {} })
console.log(finalResult);

Answer №2

Instead, here is a function that can calculate the sum of numbers at any level

If non-number values are encountered, they will take on the value of the last processed object (this behavior can be changed if needed)

Please note that array properties are not handled correctly

const objA = {
    data: {
        num: 1,
        SH: {
            propertyA: 0,
            propertyB: 3,
            propertyC: 0
        },
        text: 'objA',
        x: {
          y: {
            a: 1,
            b: 2,
            c: 3
          }
        }
    }
};
const objB = {
    data: {
        num: 2,
        SH: {
            propertyA: 0,
            propertyB: 0,
            propertyC: 1
        },
        text: 'objB',
        x: {
          y: {
            b: 4
          }
        }
    }
};
const objC = {
    data: {
        SH: {
            propertyA: 4,
            propertyB: 0,
            propertyC: 0
        },
        text: 'hello world',
        x: {
          y: {
            a: 1
          }
        }
    }
};

const addObjects = (...objs) => objs.reduce((result, obj) => {
        const fn = (obj, dest = result) => {
            Object.entries(obj).forEach(([key, value]) => {
                if (typeof value === 'object') {
                    dest[key] = dest[key] || {};
                    fn(value, dest[key]);
                } else {
                    if (typeof value === 'number') {
                        dest[key] = (dest[key] || 0) + value;
                    } else {
                        dest[key] = value;
                    }
                }
            });
            return result;
        };
        return fn(obj, result);
    }, {}
);
console.log(addObjects(objA, objB, objC));

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

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

How can I generate a list of JavaScript files to be included in a template for both production and development environments using Grunt?

I need a way to organize a list of JavaScript files in one central location, either within gruntfile.js or an external JSON file, and then dynamically implement it into a template for both development and production environments. List of JavaScript files: ...

Attempting to discover the secret to keeping a hamburger menu fixed in place once it has been expanded

Exploring this example https:// codepen.io/ducktectiveQuack/pen/mPGMRZ I had trouble understanding the code block, so I resorted to trickery (just remove the space between the '/' and the 'c' lol) My goal is to have the hamburger men ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

Vuex is throwing a mysterious ReferenceError that is leaving developers

Currently, I am developing a Single Page Application (SPA) using Vue.js and Vuex. Within this project, I have set up some data in the store and displayed it in a child component. This child component includes radio buttons that trigger a function called ge ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

The Nuxt.js authentication module remains in place and does not redirect users who are already logged

An authenticated user can still access the /login page. If I click on a link to the /login page, I am redirected to a different page successfully. However, if I manually type in /login in the URL, I am still taken to the login page even though I am already ...

Emphasize a specific line of text within a <div> with a highlighting effect

I'm looking to achieve a similar effect as demonstrated in this fiddle As per StackOverflow guidelines, I understand that when linking to jsfiddle.net, it's required to provide some code. Below is the main function from the mentioned link, but f ...

Restrict User File Uploads in PHP

I have a system set up that enables users to upload files under 200 MB. Once the file is downloaded once, it will be automatically deleted. Additionally, all files are deleted from the server after 24 hours. I am looking for a way to limit the number of up ...

AngularJS - Using filters to extract specific options from multiple <select> components

There are N "select" components generated based on JSON data, with the "options" populated by an external API. I am trying to implement a custom filter that ensures when an option is selected in one "select" component, it should not appear in the other com ...

Bring your Electronic Catalogue to life with the addition of dynamic HTML content showcasing the latest

I am creating a digital magazine but I am facing the challenge of having to deal with 200 pages in jpg format. To streamline the process, I am looking for a way to use a combination of JavaScript and PHP to avoid manually coding for each of the 200 pages. ...

Can someone guide me on how to retrieve data from a MUI table within a React project

Currently, I am retrieving data from a server in JSON format and looping through this data to display specific information. Everything is functioning as expected, but I'm encountering an issue with a Popover element that contains items with onclick ev ...

Vue: Optimizing JSON response filtering

I am struggling with filtering a JSON response using Vue. return this.offers.filter(type => type.offers == 'Junior'); When I keep it as return this.offers, the following is displayed in my HTML: {"-MN5agCddYAdy7c8GSSz": { "comp ...

Issue encountered when exporting with node and mongoose

After creating some schema and exporting the model, here is the code: var mongoose = require('mongoose'); var specSchema = new mongoose.Schema({ name: String, description:String }); var qualSchema = new mongoose.Schema({ name: Str ...

Retrieve an array of 16 elements using React in a TypeScript environment

Exploring the new React 16 feature to return array elements within the render method is throwing a TypeScript error stating "Property 'type' is missing in type 'Element[]'" const Elements: StatelessComponent<{}> = () => ([ & ...

Creative Solution for Implementing a Type Parameter in a Generic

Within my codebase, there exists a crucial interface named DatabaseEngine. This interface utilizes a single type parameter known as ResultType. This particular type parameter serves as the interface for the query result dictated by the specific database dr ...

Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code: function sendData(tableID) { var table = document.getElementById(tableID); var dataArray= new Array(); for (var i = 1;i<table.rows.length; i++){ var row = table. ...

Tips for utilizing props in a Vue component

When trying to incorporate a prop into a computed value, I encounter the following error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pa ...

How can the entire menu be closed in Bootstrap 5 when clicking on a link or outside of the page?

I'm currently utilizing BootStrap 5 for constructing my webpage. Within my page, I have a NavBar Menu containing various links. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...