-1

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"} 
2
  • 2
    You haven't indicated any way to determine which object to prefer if a given property is in both. Nor have you provided any code that attempts to solve this (which you should always do before posting to Stack Overflow). Commented Nov 17, 2021 at 15:36
  • Take a look at: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 17, 2021 at 15:38

3 Answers 3

3

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 
Sign up to request clarification or add additional context in comments.

6 Comments

it returns second object
obj3 = Object.assign(obj1, obj2) does the same work, maybe you can add it to the answer
Of course, your keys get updated to the latest object you pass.....
Always difficult to answer a question when you don't know the requirements.
its not correct. I need return obj2 value if in obj1 includes empty value
|
0

If 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)

Comments

0

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.