Crockford's method of replacing values with nested objects

/** Custom Supplant Method **/
String.prototype.customSupplant = function(obj) {
    return this.replace (/{([^{}]*)}/g,
        function (match, propPath) {
            var props = propPath.split('.');
            var result = obj;
            for (var i = 0; i < props.length; i++) {
                result = result[props[i]];
            }
            return typeof result === 'string' || typeof result === 'number' ? result : match;
        }
    );
};

Crockford may be considered a JavaScript Grand Wizard, however his prototype lacks support for replacing properties in multiple level objects.

I am seeking an enhanced version of the supplant function that can handle replacement of nested object properties like '{post.detailed}'. Can anyone assist with creating such a revised version?

Answer №1

Solving this problem shouldn't pose a challenge. Implement the following alternative replace function:

const customReplace = (original, replacement) => {
    let result = original,
        segments = replacement.split(".");
    for (let j=0; result && j<segments.length; j++)
        result = result[segments[j]];
    return typeof result === 'string' || typeof result === 'number' ? result : original;
}

Answer №2

I absolutely loathe it when individuals cram their own trash onto the original varieties in JavaScript. If I were to compose it myself, I would take the following steps... But why overlook boolean?

function replaceText(str, data) {
    return str.replace(/{([^{}]*)}/g, function (a, b) {

        // Separate the variable into its dot notation components
        var p = b.split(/\./);

        // The c variable serves as our pointer that will navigate through the object
        var c = data;

        // Iterate over the steps in the dot notation path
        for(var i = 0; i < p.length; ++i) {

            // Don't process if the key doesn't exist in the object
            // similar to how the function behaved for invalid values
            if(c[p[i]] == null)
                return a;

            // Move the pointer to the next step
            c = c[p[i]];
        }

        // Return the data if it's a string or number, otherwise do not process
        // return the initial value, e.g. {x}
        return typeof c === 'string' || typeof c === 'number' ? c : a;
    });
};

By the way, this method does not accommodate arrays; additional steps are needed to support them.

Answer №3

@Bergi's approach with added boolean support:

function checkValue(a, b) {
    var result = a,
        parts = b.split(".");
    for (var i=0; result && i<parts.length; i++)
        result = result[parts[i]];
    return typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean' ? result : a;
}

Crockford's Supplant method adapted to include boolean support:

if (!String.prototype.supplant) {
    String.prototype.supplant = function (data) {
        return this.replace(/{([^{}]*)}/g,
            function (match, key) {
                var value = data[key];
                return typeof value === 'string' || typeof value === 'n
umber' || typeof value === 'boolean' ? value : match;
            }
        );
    };
}

Wishing you the best of luck!

Link to more details

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

When using jQuery's ajax() function, it is possible to pass HTML as data and change the ampersands in URLs to &amp;

I have encountered an issue where I am capturing the HTML content of a page and attempting to send it as a string to a PHP web service using jQuery's ajax() function. However, when I receive the parameter on the PHP side, the &s in the URLs present wi ...

What is the process for setting a cookie in Next.js from a different backend server?

I have encountered an issue with my Node.js API built using Express.js. The cookie I set works perfectly fine on Postman, but for some reason, it is not functioning properly in Next.js. I set the cookie when a user logs in, but it is not appearing in the b ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

When running through Selenium web driver, JS produces inaccurate results

Currently, I am utilizing JavaScript to determine the number of classes of a specific type. However, when I run the JS code in Webdriver, it provides me with an incorrect value. Surprisingly, when I execute the same JavaScript on the Firebug console, it gi ...

Next.js deployments on Vercel are encountering issues with resolving local fonts

Currently, I am facing an issue while trying to incorporate next/fonts into my project in next.js 13.3. The setup works perfectly on my local machine, but as soon as I deploy it to Vercel, a build error arises with the message Module not found: Can't ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

Unlocking Node.js packages within React JS is a seamless process

Currently, I am developing a React Serverless App with AWS. I am looking for ways to incorporate a Node JS specific package into the React JS code without requiring Node JS on the backend. One package that I need access to is font-list, which enables list ...

Update the controller variable value when there is a change in the isolate scope directive

When using two-way binding, represented by =, in a directive, it allows passing a controller's value into the directive. But how can one pass a change made in the isolated directive back to the controller? For instance, let's say there is a form ...

AngularJS users are experiencing issues with the "See More" feature not functioning as expected

One of my tasks involves dealing with a block of text that needs to be truncated using ellipsis. To achieve this, I am utilizing jquery dotdotdot. For more information on dotdotdot, please refer to the documentation. I have created a straightforward dire ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

how can you add an object to an array in react native without altering the properties of the array

In my attempt to contract an array for use in 'react-native-searchable-dropdown', I have encountered an issue while trying to push objects into the array. Here is the code snippet that I am struggling with: let clone=[]; obj={{id:8,name:'Yyf ...

Pressing the submit button will trigger the execution of a .php script, which will then generate a popup on the screen and refresh a specific part of

I have a select form and submit button on my page, which are dynamically generated based on entries in the database. Here is the HTML output: <div id="structures"> <h1>Build</h1> <form name="buildForm" id="buildForm" method="POST" ons ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

Concealing items in a loop using Javascript

I need assistance with this issue. I am trying to hide text by clicking on a link, but it doesn't seem to be working correctly. Even though I tried the following code, I can't figure out why it's not functioning as expected. Is there a diff ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

Adding double quotes, where they haven't been added yet

I am trying to work with the following string (Very strong=="Very strong"?100:(Very strong=="Above Average"?75:(Very strong=="Average"?50:(Very strong=="Below Average"?25:(Very strong=="Cannot determine"?0:(Very strong=="Poor"?0:0)))))) My desired outpu ...

Encountering challenges with managing global variables in my Node.js application

I am facing a problem with global variables in my NodeJs application. The project involves webservices created using the express module. When a client accesses the service, a json object is sent in the request body. I extract all properties from the reques ...