Here is an alternative method that involves a classic loop approach instead of the proposed solution. This method ensures stability and avoids potential errors when parsing back the object.
It's important to note that the needle
will be treated as a regular expression, so it may be necessary to add quoting to it for better results.
Feel free to test this method and experiment with it further. You can access a working example in this JSFiddle link.
/**
* This function replaces all occurrences of a specified needle (interpreted as a regular expression) with a replacement value and returns the updated object.
*
* @param entity The object on which the replacements should be applied
* @param needle The search phrase (as a regular expression)
* @param replacement The value to replace the needle with
* @param affectsKeys[optional=true] Whether keys should be replaced
* @param affectsValues[optional=true] Whether values should be replaced
*/
Object.replaceAll = function (entity, needle, replacement, affectsKeys, affectsValues) {
// Implementation details omitted for brevity
};
The last two parameters in the function are optional, making it easy to use like this:
var replaced = Object.replaceAll( { fooman: "The dog is fooking" }, "foo", "bar" );
However, there are some ambiguous scenarios to consider, such as what should happen in these cases:
// What should be the result here?
console.log( Object.replaceAll( { x: undefined }, "fin", "baz" ) );
// How about this one?
console.log( Object.replaceAll( { x: null }, "ull", "alala" ) );
Similar uncertainties exist for boolean values and numbers:
// Will this return true or false?
console.log( Object.replaceAll( { x: true }, "true", "false" ) );
// And this one?
console.log( Object.replaceAll( { x: true }, "true", "foo" ) );
// Any predictions for these number transformations?
console.log( Object.replaceAll( { x: 1337 }, "33", "00" ) );
console.log( Object.replaceAll( { x: 1337 }, "33", "foo" ) );
Currently, my approach only handles objects and strings for replacement, leaving room for future enhancements in functionality.