Skip to content

Instantly share code, notes, and snippets.

@thisnameissoclever
Last active January 23, 2022 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thisnameissoclever/865c60769cb6a0e71e5885f1bafe47f2 to your computer and use it in GitHub Desktop.
Save thisnameissoclever/865c60769cb6a0e71e5885f1bafe47f2 to your computer and use it in GitHub Desktop.
Add one object/array to another, avoiding "pass-by-reference" pitfalls in JavaScript.
/**
* Adds one object to another, nesting the child object into the parent.
* this is to get around javascript's immutable handling of objects.
* @param name {String} - The name of the property of the parent object, in which to nest the child object. <br />For example, if the name parameter is set to "pickles" then "parent.pickles" will return the child object.
* @param child {Object} - The object that should be nested within the parent object.
* @param [parent={}] {Object} - The parent object in which to nest the child object. If the parent object is not specified, then the child object is simple nested into an otherwise empty object, which is then returned.
* @returns {Object} - A new object consisting of the parent (or an otherwise empty object) with the child object nested within it.
* @example
* //sets myNewObject to a copy of originalObject, which now also contains the original (yet un-linked) version of itself as a child, under the property name "original"
* var myNewObject = addObjToObj("original", originalObj, originalObj);
*/
function addObjToObj(name, child, parent) {
if (!parent) {
parent = {};
}
parent[name] = child;
return parent;
}
//Here's another way you can add an object to an array or another object -- break the "pass-by-reference" model, by stringifying and then parsing the object.
function addObjToArray(arr, obj) {
arr.push(JSON.parse(JSON.stringify(obj)));
return arr;
}
//And here's an object that has a method for adding other objects to itself!
var myObj = {
addObject: function(propName, obj) {
this[propName] = JSON.parse(JSON.stringify(obj));
}
};
//Here's another way, combining the first and fourth methods, to add one object to another.
//Remember that arrays are just numerically indexed objects, so this all works with them too!
myObj = {
//wip
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment