0

Let's say I have 2 objects below:

const obj1 = {
    propertyA: 'a',
    propertyB: 'b',
    propertyC: 'c',
}

const obj2 = {
    propertyA:'aa',
    propertyB:'bb',
    ....  //so many properties includes all properties in obj1
    propertyZ:'zz',
}

I want each property in obj1 has same value of property with the same name in obj2. Right now what I do is assign value of each property in obj1 :

     obj1.propertyA = obj2.propertyA;
     obj1.propertyB = obj2.propertyB;
     obj1.propertyC = obj2.propertyC;

In my actual case obj1 has lots more properties so this is pretty annoying. And so I'm looking for a better way to optimize this, may be a function in Javascript or in some library like Lodash that I don't know. Anyone know how to solve this problem please share with me.

1
  • 2
    Just loop over the keys of obj1. Object.keys(obj1).forEach(k => obj1[k] = obj2[k]); Commented Aug 8, 2021 at 10:32

2 Answers 2

2

You can simply loop over the Object.keys() of obj1, check if obj2 has a matching property and if so assign its value to obj1. Here using a for...of loop.

const obj1 = {
  propertyA: 'a',
  propertyB: 'b',
  propertyC: 'c',
}

const obj2 = {
  propertyA: 'aa',
  propertyB: 'bb',
  propertyZ: 'zz',
}

for (const k of Object.keys(obj1)) {
  if (k in obj2) {
    obj1[k] = obj2[k];
  }
}

console.log(obj1);

Sign up to request clarification or add additional context in comments.

2 Comments

Is ther any advantage over for (const k of Object.keys(obj1)) instead of for (const k in obj1)
for...in will traverse all enumerable properties including inherited properties often leading to the need to perform a hasOwnProperty check inside the loop. Object.keys only returns own properties of the objects, avoiding the need for the explicit check, but if inherited properties are desired in the loop then for...in is a fine choice.
-1

You just need to destructure your new object using the first one, thats it.

const obj1 = {
    propertyA: 'a',
    propertyB: 'b',
    propertyC: 'c',
}

const obj2 = {
    propertyA:'aa',
    propertyB:'bb',
    ...obj1,
    propertyZ:'zz',
}

console.log(obj2);
//you will get all the properties of obj1 into obj2

1 Comment

The OP wants to assign values to obj1 if obj2 has a matching property, not merge the objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.