-2

I'm working on a NodeJS project (using @babel/preset-env) and need to figure something out:

If I have two objects, one of them identical to the other but possibly minus some fields (depends on input object), how do I edit the "larger" one such that its fields are changed to the values of the matching ones from the smaller object?

That's probably worded badly, so here's an example...say I have these two objects:

const obj1 = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
}

const obj2 {
    b: 'hello',
    d: 'world'
}

What I'm wanting to do is modify obj1 in this instance such that the values of obj1.b and obj1.d get updated with the values from obj2.

Is there a way to edit the values directly, or should I just create a copy of obj1 and set values depending on whether or not they exist in obj2?

MisutoWolf
  • 1,133
  • 1
  • 18
  • 33

2 Answers2

3

Try this. You can use spread operator.

obj1 = {...obj1, ...obj2}
  • This is exactly what I needed, I forgot that spread operators even existed, I rarely use them! Thank you very much for such a quick response! – MisutoWolf Jul 31 '20 at 05:47
1

If you just want to copy the properties from obj2 over to obj1 in place (without creating a new object and replacing any matching properties that would have already existed on obj1), you can do this:

for (const [key, value] of Object.entries(obj2)) {
    obj1[key] = value;
}

Or, even just:

Object.assign(obj1, obj2)
jfriend00
  • 683,504
  • 96
  • 985
  • 979