Updating corresponding key values in two JavaScript objectsORModify matched key values

I am in need to compare two objects and update the values of the first object with the updated values from the second object. For example:

$scope.obj1={"id" : 1, "name" : "java"}
$scope.obj2={"id" : 1, "name" : "java4you", "gender" : "male"}

compare(destination, bj1, obj2);

Output in the Destination variable will be:

{"id" : 1, "name" : "java4you"}

Both objects above contain the same keys but different values. The goal is to compare obj1 and obj2 and update obj1 with values matching those in obj2.

Answer №1

To duplicate obj1, you can utilize Object.assign() to create a new variable called destination. Next, iterate through each key of obj2 by using Object.keys() and array#forEach. Check if the key exists in destination; if it does, update the value in destination with the corresponding value from obj2.

var obj1={"id" : 1, "name" : "java"},
    obj2={"id" : 1, "name" : "java4you", "gender" : "male"}

var updateObjectValue = (obj1, obj2) => {
  var destination = Object.assign({}, obj1);
  Object.keys(obj2).forEach(k => {
    if(k in destination) {
      destination[k] = obj2[k];
    }
  });
  return destination;
}
console.log(updateObjectValue(obj1, obj2));

Answer №2

If you want to compare two objects without relying on AngularJS methods, give this a try:

function findDifferences(obj1, obj2) {
  var biggerObj = obj1;
  
  if (Object.keys(obj2).length > Object.keys(obj1).length) {
    biggerObj = obj2;
  }

for (let key in biggerObj) {
  if (!biggerObj.hasOwnProperty(key)) continue;
    
    if (obj1[key] != obj2[key]) {
    console.info("Difference in '"+ key +"': "+ obj1[key] +" <> "+ obj2[key]);
    }
}
}

var $scope = {};

$scope.obj1 = {"id" : 1, "name" : "java"};
$scope.obj2 = {"id" : 1, "name" : "java4you", "gender" : "male"};

findDifferences($scope.obj1, $scope.obj2);

Just use caution with this method as it may not cover all possible scenarios.

Answer №3

With AngularJS, you have the ability to use .equal for comparison and obtain the desired outcome. If your code is not producing the expected results, it could be due to an error in the implementation.

$scope.result = angular.equals($scope.obj1, $scope.obj2);
if($scope.result === true){    
$scope.obj1 = $scope.obj2;
}

Answer №4

Give this a shot,

function mergeObjects(object1, object2)
{
    let mergedObject = {};
    for(let key in object1)
    {
         mergedObject[key] = object2[key];
     }
    return mergedObject;
}

To use it, do the following:

var mergedResult = mergeObjects(object1, object2);

Answer №5

After making some adjustments to @Bharadwaj's solution, I finally got it to work for my specific case.
It's crucial to use an if statement to filter for (... in ...) statements

    var obj1={"id" : 1, "name" : "javascript"},
        obj2={"id" : 1, "name" : "jsforlife", "gender" : "female"};

    function compare(obj1, obj2) {
      let obj = {};
      for(let k in obj1) {
         if(obj1[k] !== obj2[k]) {
           obj = Object.assign({}, obj1, obj1[k] = obj2[k]);
         }
         
      }
      return obj;
    }

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

Switch the script: convert from jQuery to traditional JavaScript code

I've been trying to transition from using jQuery for a toggle script on my website to just using normal JavaScript in order to clean up the code. However, I'm having trouble converting the existing jQuery code into vanilla JavaScript. Here is th ...

"Encountering a Twilio POST error when attempting to send SMS

After spending hours struggling with this issue, I could definitely use some assistance. The problem I'm facing involves sending an SMS message through Twillio on a click event in Angular. The function SendTestMessage is called when the button is cli ...

Exploring the capabilities of SVG and audio integration in web browsers

I am curious if it's possible to incorporate audio into an SVG file in a web browser. I came across this thread here, but unfortunately, I can't leave a comment =/ I tried implementing the code from this website, but it doesn't seem to work ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

Transforming the format from YYYYMMDD using MomentJS

Currently, I have a date in the format of YY as shown here: 20141229. I am attempting to convert it into Timestamp format. I attempted using moment(date).format('x'), but received an "Invalid date" error. I'm unsure of how to accomplish this ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

Spring REST service prevents Cross-Origin Requests with AJAX

Having Trouble Accessing Spring REST Service My spring service @RequestMapping(value = "/MAS/authenticate", method = RequestMethod.POST) public ResponseEntity<Map<String, String>> authenticate(@RequestBody Subject subject) { Map<String ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Symfony seems to be dropping my session unexpectedly during certain requests

Currently dealing with angular 2, I am encountering issues with requesting symfony where certain requests cause the sessions to be lost. Strangely enough, some requests work perfectly fine while others do not. If anyone has any insight or advice on what co ...

How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decid ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Display irregularly spaced time samples from a MySQL database on a Google Line Chart using a PHP query

Currently, I am utilizing a Line Chart from Google to display data fetched from a MySQL database involving various variables at different time intervals. Although the sample time is set at 1 minute, there are occasions where some data points are lost (for ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

What is the order of execution for AngularJS directives?

When using an AngularJS custom directive that executes a function, followed by a regular directive like ng-repeat, which one takes precedence in execution? For instance, if I have a select element with a custom multi-select directive and an ng-repeat dire ...

Unlocking Controller Functions in AngularJS Directives: A Step-by-Step Guide

Here is a sample controller and directive code: class DashboardCtrl { constructor ($scope, $stateParams) { "ngInject"; this.$scope = $scope; this.title = 'Dashboard'; } loadCharts () { // some logic here } } export def ...

Refreshing a div by replacing its content with text entered into an input field

I'm exploring React and attempting to create a basic div that dynamically changes its text based on input from an input box. Below is the code I have written so far: import React from "react"; import ReactDOM from "react-dom"; const rootElement = d ...

What could be causing the malfunction with Angular?

What seems to be the issue? <!doctype html> <html lang="en" ng-app='SOO'> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div ng-controller='someController ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

Is there a way to capture all ajax responses?

Is it possible to capture all responses from an ajax request, regardless of the library being used such as jQuery, prototype, or just the vanilla XMLHttpRequest object? I am looking for a way to append to any existing handler without removing it. Thank y ...