Skip to content

Instantly share code, notes, and snippets.

@ORESoftware
Created June 25, 2019 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ORESoftware/d83682d73433c79ac2c69339e3672182 to your computer and use it in GitHub Desktop.
Save ORESoftware/d83682d73433c79ac2c69339e3672182 to your computer and use it in GitHub Desktop.
spread operator to merge / mixin objects
const a = {
a: {
b: {
c: 4,
d: 'str'
}
}
};
const b = {a: {b: {c: 5}}};
console.log({...a,...b}); // { a: { b: { c: 5 } } }
// now reverse the arguments
console.log({...b,...a}); // { a: { b: { c: 4, d: 'str' } } }
@KSoto
Copy link

KSoto commented Jun 25, 2019

Oh I see what you mean. The order matters.

What I tried in regards to https://stackoverflow.com/questions/56744955/inclusive-mixin-with-js is the same as your second console log

const b = {}; 
const a = {
  a: {
    b: {
      c: 4,
      d: 'str'
    }
  }
};
const object3 = {...b, ...a };

console.log(JSON.stringify(object3)); // {"a":{"b":{"c":4,"d":"str"}}}

@ORESoftware
Copy link
Author

ORESoftware commented Jun 25, 2019

Yeah the desired result (I didn't make it that clear), is { a: { b: { c: 5, d: 'str' } } } (5 not 4)

there is really no reason to expect the spread operator to work on shared keys - it will always just overwrite a key using the new one. so in this case, either the entire a key/value is taken from the first or the second object, but they aren't merged in any sophisticated fashion.

@KSoto
Copy link

KSoto commented Jun 25, 2019

Oooh I see, thank you for clearing that up! I think I was ignoring the values xD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment