Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks.

The objective is to generate a list of paths that GULP can utilize, but they require processing before that. I am replacing the 'placeholder' values in the paths array with their corresponding substitution values from the subs array through a loop until all paths are converted to literal form.

An issue arises in identifying the paths that remain unprocessed by the loop, such as '../test4' (literal paths), so I can handle them separately after completion.

This is the initial progress with some sample data for demonstration:

function updatePaths(substitutionsArray, pathArray) {
    var updatedPaths = [];

    pathArray.forEach(function (path, index, array) {
        console.log('Processing line ' + (index + 1) + '... ' + path);
        Object.keys(substitutionsArray).forEach(function (placeholder) {
                var substitution = substitutionsArray[placeholder];

                var fixedPath = path.replace(placeholder, substitution);

                if (fixedPath == path) {
                    console.log('No replacement found in path ' + path + ' for placeholder ' + placeholder);
                } else {
                    console.log('Replacement discovered in path ' + path + ' for placeholder ' + placeholder + ', resulting in ' + fixedPath);                    

                        updatedPaths.push(fixedPath);
                }
            }
        )
    });
    console.log(updatedPaths);
    return updatedPaths;
}

var substitutions = {
    "@COMMON_JS@": "/test1",
    "@COMMON_ROOT@": "/test2",
    "@COMPONENT_ROOT@": "/test3",
    "@COMPONENT_WEB_ROOT@": "/components"
};
var filepaths = ['@COMMON_JS@/test1', '@COMMON_ROOT@/test2', '@COMPONENT_ROOT@/test3', '../test4', '../../test5'];

output = updatePaths(substitutions, filepaths);

console.log(output);

return;

If you have any recommendations on how to approach this task more effectively, please let me know.

Thanks in advance - Dave

Answer №1

The paths cannot be retrieved from the console. When using Console.log, it always returns undefined. If you wish to display the value you pass in, you can create a function that logs it like this:

function log() { console.log.apply(console, arguments) return arguments }

This function will return the arguments you input into it. More information about the arguments object can be found here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

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

Is it possible to utilize Vue.js' v-if directive to validate if a certain value is present within an array

In my form, I have a checkbox and I want to be able to use v-if directly to display or hide sections based on the selected checkbox values. Can this be done using v-if, or do I need to use watch:? ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

The class functions perfectly under regular circumstances but ceases to operate once it is initialized

I'm currently developing a bluetooth remote in React Native. The issue I am facing is that my BLE class works perfectly on its own, but certain sections of code seem to malfunction when implemented within another class. import BLE from './Core/BL ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

Mastering the art of MUI V4: Implementing conditional row coloring

I've encountered an issue with my basic Material UI v4 datagrid. I'm attempting to change the color of any row that has an age of 16 to grey using color: 'grey'. However, I'm finding it challenging to implement this. The documentat ...

Using an AJAX post request will result in receiving an HTML element, especially when an attachment is included with Paperclip

I've created an innovative application where users can share their stories through ajax submissions and engage with other readers by commenting on the stories using ajax as well. The technology stack I'm working with includes Rails 3.0.3, ruby 1. ...

Is there a way to reset the dynamic flexslider when a click event occurs?

Seeking a way to refresh the flexslider on a click event. I have embedded the flexslider in a Bootstrap pop-up and need it to update when the user clicks. The issue arises when I try to refresh the slider as it fails to display properly, likely due to losi ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

What is the most effective method for discerning the availability of fresh data?

Many highload websites are able to notify their users of new messages or topics in real-time without the need for page refreshing. How do they achieve this and what approaches are commonly used? There appear to be two main methods: Continuously querying ...

What is the method for updating the form action to alter the hash without causing a page reload?

My website is designed to show dynamic data based on the information following the '#' in the URL. Surprisingly, when I manually change this value in the URL, the page doesn't reload. However, if I modify it within a form on the site, the we ...

What is the process for passing an object in the http.send() method?

I'm currently working on sending a POST request to a specific URL using the code below. However, when passing an object to the http.send(params) function, it's resulting in a (400) bad request error. I'm having trouble pinpointing the issue ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

What is the best way to store selected items from a multi-select box in AngularJS that is generated using ng-repeat?

I have a scenario where I need to handle a group of select boxes instead of just one. Each select box holds a different option, and when the user changes their selection, I want to save that value in a variable or an array. I've managed to do this for ...

Charts created using Google VisualizationORThe visual representations

My chart is currently not displaying at 100% width as I intended. I would like the chart to span from the beginning to the end of the container. https://i.stack.imgur.com/Xjw6g.png Here's my code snippet: test.controller('testCtrl', [&apo ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

The spreading of personalized events

I am expecting my CustomEvent to be propagated from the document to all the DOM elements. However, for some unknown reason, it is not happening. Can you point out what mistake I might be making? <html> <script> function onLoad() { var myDi ...

Getting request parameters within Model in Loopback can be done by accessing the `ctx`

common/models/event.json { "name": "Event", "mongodb": { "collection": "event" }, "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "http": { "path": "organizer/:organizer_id/events" }, "properties": {}, "va ...

Utilize date-fns to style your dates

Struggling to properly format a date using the date-fns library. The example date I'm trying to work with is 2021-09-20T12:12:36.166584+02:00. What am I doing wrong and what is the correct approach? Here's the code snippet I have so far: import ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...