Skip to content

Instantly share code, notes, and snippets.

@Log-of-e
Created July 3, 2020 16:34
Show Gist options
  • Select an option

  • Save Log-of-e/11d844de7373f2cdcc8108a9760540b3 to your computer and use it in GitHub Desktop.

Select an option

Save Log-of-e/11d844de7373f2cdcc8108a9760540b3 to your computer and use it in GitHub Desktop.
Clone and merge JS objects
//code written by Sham Bhangal, Senior Web application developer
// https://www.quora.com/profile/Sham-Bhangal
// on site: https://www.quora.com/Vue-js-seems-to-be-much-more-productive-than-React-js-Why-do-some-still-use-React
class StoreHelpers {
static deepClone(obj) {
var out, v, key;
out = Array.isArray(obj) ? [] : {};
for (key in obj) {
v = obj[key];
out[key] = (typeof v === "object") ? StoreHelpers.deepClone(v) : v;
}
return out;
}
static mergeBIntoA(a, b) {
// helper function, merges two objects. eg. if a={prop1:10, prop2:{prop3:30}},
// and b={prop1:20, prop2:{prop4:40}} , then the result will be {prop1:10, prop2:{prop3:30, prop4:40}},
// which is not what object.assign() would give, which would be {prop1:10, prop2:{prop4:40}} because of
// the collision on prop2, causing overwrite.
var prop;
for (prop in b) {
// If a.property does not exist or is a value (string, number, boolean), replace it with b.property.
// NB - we merge b into a even if a[prop] already equals b[prop] (checking first is slower than just
// making the change).
if (!a.hasOwnProperty(prop) || ( typeof(a[prop]) !== "object") ) {
a[prop] = b[prop];
}
// If we have a nested level, recurse down to the nested level to merge children.
if (typeof(b[prop]) === "object") {
StoreHelpers.mergeBIntoA(a[prop], b[prop]);
}
}
return a;
}
}
@Log-of-e
Copy link
Copy Markdown
Author

Log-of-e commented Jul 3, 2020

@Log-of-e
Copy link
Copy Markdown
Author

Log-of-e commented Jul 3, 2020

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