Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two objects with the same keys and I need to merge them preserving the values of the first object. For instance:
JavaScript
var obj1 = {
	1: "John",
	2: "Tom",
	3: "Harry"
};

var obj2 = {
	1: "Doe",
	2: "Jones",
	3: "Newman" 
};

Desired output:
JavaScript
var obj3 = {
	1: "John Doe",
	2: "Tom Jones",
	3: "Harry Newman"
};

This is what I've tried:
JavaScript
var obj3 = {};

for (var item in obj1) {
	obj3[item] = obj1[item] + " " + obj2[item];
};

It works. But is there a better/simpler way to achieve what I need?

What I have tried:

JavaScript
var obj3 = {};

for (var item in obj1) {
	obj3[item] = obj1[item] + " " + obj2[item];
};
Posted
Updated 6-Oct-23 12:18pm
v2

1 solution

There is nothing wrong with your code and it is down to the point, however, if you're looking for a more concise and modern way you can use the 'Object.keys' method along with 'Array.prototype.reduce' to create your merged object.
The Object.keys() static method[^]
The reduce() method[^]

JavaScript
const obj1 = {
  1: "John",
  2: "Tom",
  3: "Harry"
};

const obj2 = {
  1: "Doe",
  2: "Jones",
  3: "Newman"
};

const obj3 = Object.keys(obj1).reduce((result, key) => {
  result[key] = `${obj1[key]} ${obj2[key]}`;
  return result;
}, {});

console.log(obj3);


I have created a fiddle for you which gives the desired output -
Merged object[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900