return single object. return second parameter with first parameter values. return parameter not hard coded.
function addPropertiesToObject(obj1, obj2) {
var param = {}
for (var things in obj1) {
param[things] = obj1[things];
}
for (var things in obj2) {
param[things] = obj2[things];
}
return param;
}
Again, if both objects have the same key, that value will be overwritten by the second.
Edit to show adding obj1 to obj2 instead of obj2 to obj1
function addPropertiesToObject(obj1, obj2) {
var param = {}
for (var things in obj2) {
param[things] = obj2[things];
}
for (var things in obj1) {
param[things] = obj1[things];
}
return param;
}
const obj1 = {name: "John"}
const obj2 = {name: "Jane"}
const obj3 = {email: "example@domain.com"}
console.log(addPropertiesToObject(obj1,obj2))
//Return: {name: "John"}
console.log(addPropertiesToObject(obj1,obj3))
//Return: {email: "example@domain.com", name: "John"}
You can also accomplish this without looping
function addPropertiesToObject(obj1, obj2) {
return {...obj2,...obj1}
}
const obj1 = {name: "John"}
const obj2 = {name: "Jane"}
const obj3 = {email: "example@domain.com"}
console.log(addPropertiesToObject(obj1,obj2))
//Return: {name: "Jane"}
console.log(addPropertiesToObject(obj1,obj3))
//Return: {email: "example@domain.com", name: "John"}
If you would like to keep the contents of both objects, you can do something like:
function addPropertiesToObject(obj1, obj2) {
var param = {...obj2}
for (var things in obj1) {
if(param[things]) param[things] = [param[things], obj1[things]]
else param[things] = obj1[things];
}
return param;
}
const obj1 = {name: "John"}
const obj2 = {name: "Jane"}
const obj3 = {email: "example@domain.com"}
console.log(addPropertiesToObject(obj1,obj2))
//Return: {name: ["Jane","John"]}
console.log(addPropertiesToObject(obj1,obj3))
//Return: {email: "example@domain.com", name: "John"}
Or changing the name of the key like:
function addPropertiesToObject(obj1, obj2) {
var param = {...obj2}
for (var things in obj1) {
if(param[things]) param[things+"1"] = obj1[things]
else param[things] = obj1[things];
}
return param;
}
const obj1 = {name: "John"}
const obj2 = {name: "Jane"}
const obj3 = {email: "example@domain.com"}
console.log(addPropertiesToObject(obj1,obj2))
//Return: {name: "Jane", name1: "John"}
console.log(addPropertiesToObject(obj1,obj3))
//Return: {email: "example@domain.com", name: "John"}