Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.