Created
July 3, 2020 16:34
-
-
Save Log-of-e/11d844de7373f2cdcc8108a9760540b3 to your computer and use it in GitHub Desktop.
Clone and merge JS objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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; | |
| } | |
| } |
Author
Author
//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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//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