Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={
  name:"Sarah",
  age:"35",
  jobTitle:"Manager"
}

var person2={
  name:"Sarah Sanders",
  age:"35",
  jobTitle:"Manager"
}

//the name value has been updated in the above object, so a new object is needed like

desired output

var updatedPerson={
name:"Sarah Sanders"
}

//is it possible to create new objects in this manner for JavaScript objects?

Answer №1

When it comes to determining the desired output for different keys, I decided to include both values in an array for flexibility. Feel free to adjust this according to your needs.

Assumption: It is assumed that the keys present in both objects are the same.

var obj1 = { name: 'jhon', age: '26', role: 'intern' };
var obj2 = { name: 'jhon berner', age: '26', role: 'intern' };
var newObj = {};
Object.keys(obj1).forEach((key) => {
    if (obj1[key] !== obj2[key]) {
        newObj[key] = [obj1[key], obj2[key]];
    }
});

console.log(newObj);

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

"Utilizing the same generic in two interface properties in Typescript necessitates the use of the

I have created an interface as follows: interface I<T>{ foo: T arr: T[] } After defining the interface, I have implemented an identity function using it: const fn = <T>({foo, arr}: I<T>) => ({foo, arr}) When calling this function l ...

Tips for transferring a value from a Next.js route to a physical component

So, I encountered some issues while creating a Next.js project related to the database. To solve this problem, I connected to Vercel's hosted database. After successfully inserting and selecting data into the database using routes, I wanted to enhance ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

Determine the Placement of Bootstrap Popover by Utilizing SVG and Mouse Coordinates

Is there a way to dynamically reposition the popover that currently appears to the right of the Circle SVG? I would like to either base its position on the user's mouse click within the CircleSVG or move it to the exact center of the SVG, including bo ...

prevent parent jQuery functions from interfering with child function execution

I am facing an issue with conflicting jQuery functions between parent and child elements. The child function is a bootstrap function, while the parent is a custom function. The main objective is to limit the height of the parent div (refer to the code belo ...

Matching the Expected Type with Custom SWR Hook's Return Type

Currently, I am working on integrating swr into my project to create a custom block hook using generics. The goal is to have this hook creator accept mapParamsToKey and request methods as parameters and generate an SWR hook function. However, there seems t ...

Exploring Angular 17's unique approach to structuring standalone components

Is something wrong with my code if I can only see the footer, header, and side-nav components on localhost? How can I fix this? app.component.html <div class="container-fluid"> <div class="row"> <div class=&q ...

Using forEach Loop with Promise.all in Node.js

I am seeking a solution for a task where I need to read a directory, copy its contents, and create a new file within that same directory. function createFiles(countryCode) { fs.readdir('./app/data', (err, directories) => { if (err) { ...

What distinguishes res.send from app.post?

I'm just starting to learn about express and HTTP. I've heard that the express library has app.get, app.post, and res.send methods. From what I gather, app.get is used for GET requests and app.post is used for POST requests. How does res.send fit ...

Unlock the power of Redux: Crafting specialized selectors with parameters

I am currently working with a state that contains a map array of data. I find myself needing to select a single object from this array. To achieve this, I can retrieve the entire array in my component using: function mapStateToProps (state) { return { ...

Types of Content in Solr Responses

My journey with Solr has been enlightening, but I've hit a bump in the road. When querying Solr using: curl "http://localhost:8983/solr/myCollection/select?q=*:*&wt=json&rows=0" I receive a webpage displaying the JSON response. However, the ...

How to prevent all boxes in jQuery from sliding up at the same time

I am encountering an issue with 36 boxes where, upon hovering over the title, the hidden text below it should slide up. However, all 36 boxes are sliding up simultaneously instead of just the one being hovered over. Below is the script I am currently using ...

``There seems to be an issue decoding the JSON array

I am currently working on a PHP script to decode JSON data and insert the objects into my database. However, I am encountering an error: Fatal error: Cannot use object of type stdClass as array in phptest.php on line 21 $postdata = file_get_contents("php: ...

What is the best way to update the text on buttons once they've been clicked for a variety of buttons

I'm encountering an issue with multiple buttons where clicking on any button causes the text to change on the first button, rather than the one I actually clicked on. All buttons have the same id, and using different ids for each button seems impracti ...

"Step-by-step guide on creating a popup window for editing a row using ng-grid and AngularJS

I recently started diving into angular-js and I'm really impressed with how cool it is. In my search, I came across http://angular-ui.github.io/ng-grid/, which seems to be a user-friendly tool. However, I'm grappling with figuring out how to disp ...

There was an issue parsing the parameter '--request-items' due to invalid JSON format. Decoding failed as no JSON object could be found

My current environment includes AWS cloud, DynamoDB, AWS Cloud9, Python, and JSON. I'm attempting to write these elements into a DynamoDB table using the command aws dynamodb batch-write-item --request-items file://Sensors.json in my Cloud9 CLI. How ...

Troubleshooting await and async functions in Express.js applications

How can I create an array like the one shown below? [{ "item":"item1", "subitem":[{"subitem1","subitem2"}] },{ "item":"item2", "subitem":[{"subitem3","subitem4&q ...

Simple Java methods for organizing and finding information in a json array

Here is an example of my Json file structure: { "Hello" : [{ "CommentId":28227, "Comments":"User Philip John has added a new file", "DisplayComments":"User <a id='getUser' data='205' >Philip John</a> has a ...

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...