Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties?

Check out this method, but is it the most optimal solution?

var obj = {
   'a' : 'The fooman poured the drinks.',
   'b' : {
      'c' : 'Dogs say fook, but what does the fox say?'
   }
}

console.log (JSON.parse(JSON.stringify(obj).replace(/foo/g, 'bar')));

Test it on Fiddle: http://jsfiddle.net/93Uf4/3/

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a button that allows updates without refreshing the page can be achieved by implementing

Here are the items I have: <table> <tr> <th> id </th> <th> name </th> <th> update </th> </tr> <tr> ...

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

The lightbox feature seems to be malfunctioning, despite having successfully loaded jQuery

Struggling to activate lightbox on my gallery. Jquery is functioning as verified with an alert() in the documet.ready(). However, lightbox does not seem to be working properly. Only the links are operational. Below is a snippet of my code: <!DOCTYPE ht ...

Utilize Babel transpiling specifically for necessary Node modules

My current setup in nextjs is configured to handle ES6 code for IE11. module.exports = { poweredByHeader: false, distDir: "ssr_build", webpack(config) { config.node = { fs: "empty", net: "empty", tls: "empty" } config.plugins = config.plugi ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...

Error: The parameter "q" provided in the Google Maps Embed API is

Currently, I am developing a Web Application using NodeJs, Express, and Pug/Jade. The pug code below is functional: iframe#map(width="100%", height="600", frameborder="0", style="border:0" src='https://www.google.com/maps/embed/v1/place?' + ...

What is the best way to fill HTML tables using an ajax response?

This is a Laravel blade view/page that requires updating without the need to refresh the entire page. The blade.php code functions correctly and retrieves data from a MySQL database, but there seems to be an issue with the AJAX and JavaScript implementati ...

Using Selenium WebDriver and JavaScript: Enabling Chrome to Download Multiple Files at Once

After scouring through multiple documents for hours like https://www.selenium.dev/documentation/en/webdriver/js_alerts_prompts_and_confirmations/ as well as https://chromedriver.chromium.org/capabilities and I was unsuccessful in finding a solution wit ...

Having trouble with JavaScript concat function not behaving as it should? Can you provide more details to

I am trying to extract all the cities from an object that contains country names as keys and arrays of cities as values. However, my approach seems to be failing and I can't figure out why. var cities = { "United Kingdom": ['london'], ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

Switch Object to WebElement or SearchContext in JavaScript

Looking for the best way to convert an Object to WebElement or SearchContext using JavaScript? In Java, casting as `(WebElement)` or `(SearchContext)` works fine. However, attempting the same in JavaScript with `as Webelement` or `as SearchContext` result ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

Ways to conceal submenu when clicking away from the navigation bar

I am looking to create a directive that will generate a navigation bar. Check out my code on JSFiddle here. Here is the code snippet from index.html : <html lang="fr" ng-app="activity" id="ng-app"> <div ng-controller="mainCtrl"> ...

Using AJAX to query a database and updating a div tag with the submitted form entries

I need assistance in setting up a webpage with an AJAX form. The idea is that upon submission, the form's values will be used to search and query a database for results, which will then be displayed in the same DIV as the form. Any guidance or help o ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

Using Ant Design with Formik to dynamically set field values in a form

When I click the "Change" button in an Antd table with data, the entire line of data is passed to a function as an object. However, I am having trouble inserting the data into the fields. What should I do? How can I set data to Antd input using an externa ...

Need guidance on dependencies when loading modules for use in a function or class? Let me point you in the right direction

After experimenting with some code samples, I managed to find a solution that works for the given challenge in the doctests: def remove(sub, s): """ >>> remove('an', 'banana') 'bana' >>> ...