Combining arrays of properties in two objects

Below are the JavaScript objects I am working with:

Object A:

0300 : ["295", "293", "298"],
0800 : ["293", "298"],
0930 : ["295"],
1130 : ["297", "293", "298"],
1230 : ["295"]

Object B:

0300 : ["297"],
0800 : ["297"],
0930 : ["293"],

I aim to merge these two objects to create a final object that looks like this:

0300 : ["295", "293", "298", "297"],
0800 : ["293", "298", "297"],
0930 : ["295", "298", "293"],
1130 : ["297", "293", "298"],
1230 : ["295", "298"]

I attempted using new_object['0300'].push within a loop, but it did not yield the desired outcome.

What is the best way to merge JavaScript objects efficiently? Any recommended practices?

Answer №1

Give this a shot:

for (let property in fresh_object){
    if(stale_object.has(property)){
        fresh_object[property] = fresh_object[property].combine(stale_object[property]);
    } 
}

Answer №2

Another option is utilizing jquery's $.merge() function.

var combinedArray = $.merge(existingArray, newArray);

Click here

Answer №3

I believe the correct syntax should be new_object[0300].push, not new_object['0300'].push. Give it a try with new_object[0300].push and observe the results, although they may seem unusual.

var newObject = {0300 : ["295", "293", "298"],0800 : ["293", "298"],0930 : ["295"],1130 : ["297", "293", "298"],1230 : ["295"]}
var oldObject = {0300 : ["297"],0800 : ["297"],0930 : ["293"]}
newObject[0300].push(oldObject[0300])
//console outputs: ["295", "293", "298", ["297"]] 

To resolve this issue, I recommend using the concat method.

var newObject = {0300 : ["295", "293", "298"],0800 : ["293", "298"],0930 : ["295"],1130 : ["297", "293", "298"],1230 : ["295"]}
var oldObject = {0300 : ["297"],0800 : ["297"],0930 : ["293"]}

newObject[0300].concat(oldObject[0300])
//console outputs: ["295", "293", "298", "297"]

To merge two Json objects, follow these steps:

For further information on how to dynamically merge properties of two JavaScript objects, please visit How can I merge properties of two JavaScript objects dynamically?

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Answer №4

In order to combine properties with the same key in two objects, a utility function must be written that takes a merge strategy as an argument.

The process involves iterating over the keys of the second object and determining whether to merge the value into the first object (if there is already a property with the same key) or simply copy it over. The current implementation mutates the first object (o1):

function merge_keys(o1, o2, merge) {
  var keys2 = Object.keys(o2), key;

  for (var i = 0; i < keys2.length; i++) {
    key = keys2[i];
    o1[key] = o1[key] ? merge(o1[key], o2[key]) : o2[key];
  }
}

The merging strategy can then be defined, such as:

function concat(a, b) { return a.concat(b); }

Finally, the function can be called using the specified merge strategy:

merge_keys(new_object, old_object, concat);

To achieve this more concisely in ES6 using for...of:

function merge_keys(o1, o2, merge) {
  for (var k of Object.keys(o2)) {
    o1[k] = o1[k] ? merge(o1[k], o2[k]) : o2[k];
  }
}

Alternatively, if you prefer using Array#forEach:

function merge_keys(o1, o2, merge) {
  function maybe_merge(k) { o1[k] = o1[k] ? merge(o1[k], o2[k]) : o2[k]; }

  Object.keys(o2).forEach(maybe_merge);
}

Answer №5

Finally cracked the code...

const updated_object = {};

const new_props = Object.getOwnPropertyNames(new_data);
const old_props = Object.getOwnPropertyNames(old_data);
let new_props_length = new_props.length;
let old_props_length = old_props.length;

if (new_props_length > old_props_length) {
    while (--new_props_length) {
        const prop_name = new_props[new_props_length];
        
        if (old_data[prop_name]) {
            updated_object[prop_name] = new_data[prop_name].concat(old_data[prop_name]);
        } else {
            updated_object[prop_name] = new_props[new_props_length];
        }
    }

} else {
    while (--old_props_length) {
        const prop_name = old_props[old_props_length];
        
        if (new_data[prop_name]) {
            updated_object[prop_name] = old_data[prop_name].concat(new_data[prop_name]);
        } else {
            updated_object[prop_name] = old_props[old_props_length];
        }
    }
}

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

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Integrating chat functionality with a structured data format

Considering creating a collaborative communication platform, I am contemplating whether to develop a comprehensive application in JavaScript with MVC architecture or utilize it solely for managing message delivery using Node.js and socketIO. Would it be m ...

Utilizing jQuery for asynchronous image uploading

Just started learning jQuery and I'm having trouble uploading a jpg image file using the ajax method. It seems like it's not working properly. Can anyone guide me through this process? HTML <form action="" method="POST" enctype="multipart/fo ...

Locate items within a nested array of objects

I need to extract a specific object from a JSON array with nested objects by using the key name. I've attempted various methods but haven't found a generic solution yet. let data = {"role":"http://www.icai.org/xbrl/taxonomy/role/in ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

Mutation observer fails to observe an element if it is housed within a function

I am attempting to initialize the liveChatAvailable value as true and set the isLoading value to false once the crispClient element loads onto the page. However, when the observer object is placed within a function, the if (crispClient) code does not exec ...

What is the best way to retrieve HTTP tags within a map function in React?

I'm currently working on a dynamic bar chart with multiple levels. I utilized the map function to generate the chart data and did console logging to ensure everything is in order. However, despite the code working properly, the return tag doesn't ...

What is the best way to display a chosen item in a text input field?

https://i.stack.imgur.com/Qe5Ds.png Looking to create a similar design, but lacking the necessary expertise. What steps should I take or what is the specific term for this style? Seeking assistance in implementing this using jQuery, PHP, or JavaScript. A ...

Which is Better for Tabbed Content: Ajax Control or Javascript? (Choosing between the two for an aspx page with

On my ASP.NET website with C# as the code behind, I've implemented tabbed content on one of the pages in two different ways. Now I'm trying to determine the best approach. One method involves using JavaScript to swap divs based on which tab is cl ...

Evaluation of Google Closure Library's performance

When researching the performance of JavaScript libraries, I come across numerous websites that compare the speed of popular libraries including: jQuery (known for being slow) Prototype (especially sluggish in IE) Dojo (considered the fastest when it come ...

PowerShell 5 returns a string instead of a JSON object for REST requests

Currently, I'm sending a GET request to a REST endpoint and receiving an object as a response. However, the Content subcategory and data within that are both of type String. How can I ensure that the entire response is formatted as an object so that I ...

Identifying the user's location within the application and dynamically loading various Angular scripts

Currently, I am working on a large-scale web application using Laravel and Angular. In this project, I have integrated various angular modules that come with their own controllers, directives, and views. One challenge I am facing is the need to load diffe ...

What is the best way to automatically adjust the quantity and total cost for every SKU using JavaScript?

Currently, I am developing the functionality for a virtual store's shopping cart. At the core of this feature lies a Cart class that manages data and executes calculations. This specific class does not interact with the HTML document or the DOM; its p ...

Leverage JSON data using props in React JS

Currently, my data is formatted in JSON and successfully populated into props known as foxFooterData. Upon inspecting the console.log result of foxFooterData.data, the following information is visible: https://i.sstatic.net/8htNG.png I am attempting to r ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

Incorrect use of the jQuery .height() method

I am working on creating a responsive div with a sloped edge that needs to adjust according to the screen size. I have successfully maintained a consistent angle across all screen sizes, but I am facing an issue where the height calculation for $('#sl ...

obtain a promise from an asynchronous function within a synchronous function

My issue arises when attempting to verify user credentials. The promise returned from login() is not resolved yet, resulting in loginResult being Promise{}. I understand that I need to await the result somehow, but I am struggling to find a solution. Any ...

Unmounting the event post transitioning to a new page

In a component, I have implemented code that checks if the component is visible when scrolling. Here's what the code looks like: constructor(props) { super(props); this.handleScrollAnimation = this.handleScrollAnimation.bind(this); ...

ReactJS: Oops! Looks like there's an issue with the element type - it's invalid. We were expecting a string

I am in the process of setting up a basic server-side rendered React application. Listed below are the steps I have taken: Step 1: Creating a new React app using create-react-app: npx create-react-app my-ssr-app Step 2: Installing necessary dependencies: ...