I have first object
obj1 = {lastName: "", address1: "Some address"} and second object:
obj2 = {lastName: "Salivan", address1: "1200 Getty Center Dr"} in the result object:
obj3 = {lastName: "Salivan", address1: "Some address"} I have first object
obj1 = {lastName: "", address1: "Some address"} and second object:
obj2 = {lastName: "Salivan", address1: "1200 Getty Center Dr"} in the result object:
obj3 = {lastName: "Salivan", address1: "Some address"} The easiest way for me would be to do the following:
const newObject = { ...obj1, ...obj2, } The thing is, it will override your values! So better not merge two similar objects into one, usually it is used to update values of an object or merge different objects into one.
As @AlexSp3 suggested, you can also:
obj3 = Object.assign(obj1, obj2) For your specific case:
const obj3 = { key1: '', key2: '', } if (!obj1.key1) { obj3.key1 = obj2.key1; } else { obj3.key1 = obj1.key1; } // ... repeat with key2 obj3 = Object.assign(obj1, obj2) does the same work, maybe you can add it to the answerIf the objective is to select the non falsey values...
let obj1 = { lastName: "", address1: "Some address" } let obj2 = { lastName: "Salivan", address1: "1200 Getty Center Dr" } let result = Object.fromEntries( Object.entries(obj1).map(([key, value]) => { return [key, value || obj2[key]] }) ); console.log(result) Without overwriting values:
const obj1 = { key1: 1, key2: 2 } const obj2 = { key2: 3, key3: 4 } function mergeObjects(obj0, obj1) { // merge object keys into array const joined = [...Object.keys(obj0), ...Object.keys(obj1)] // remove duplicates const uniqueKeys = [...new Set(joined)] // merge obj0 and obj1 into new Object // obj1 overrides obj0 const newObject = {} uniqueKeys.forEach(key => { if (obj0[key] !== undefined && obj1[key] !== undefined) { newObject[key] = [obj0[key], obj1[key]] } else if (obj0[key] === undefined && obj1[key] !== undefined) { newObject[key] = obj1[key] } else if (obj0[key] !== undefined && obj1[key] === undefined) { newObject[key] = obj0[key] } else { console.log('OBJECT MERGING ERROR') } }) return newObject } console.log(mergeObjects(obj1, obj2))