What is the best way to remove words from an object's value that begin with a specific keyword using JavaScript?

Here is a sample array. I need to remove the words row-? from the className property.

[
  {
    type: "text",
    name: "text-1632646960432-0",
    satir: "1",
    className: "form-control col-lg-3 row-1"
  },
  {
    type: "text",
    name: "text-1632646974512-0",
    satir: "1",
    className: "form-control col-lg-6 row-8"
  }
]

The desired result should look like this.

[
  {
    type: "text",
    name: "text-1632646960432-0",
    satir: "1",
    className: "form-control col-lg-3"
  },
  {
    type: "text",
    name: "text-1632646974512-0",
    satir: "1",
    className: "form-control col-lg-6"
  }
]

Is there a way to achieve this? Also, how can I eliminate any trailing spaces?

Answer №1

1) One approach is to iterate over the array, then split the className, filter it based on specific criteria, and finally join it back together.

const arr = [
  {
    type: "text",
    name: "text-1632646960432-0",
    satir: "1",
    className: "form-control col-lg-3 row-1",
  },
  {
    type: "text",
    name: "text-1632646974512-0",
    satir: "1",
    className: "form-control col-lg-6 row-8",
  },
];

const result = arr.map((o) => ({
  ...o,
  className: o.className
    .split(" ")
    .filter((s) => !s.startsWith("row"))
    .join(" "),
}));

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

2) Another method involves using regex pattern /\s*row-\d+/g

https://i.stack.imgur.com/DwHQR.png

const arr = [{
    type: "text",
    name: "text-1632646960432-0",
    satir: "1",
    className: "form-control col-lg-3 row-1",
  },
  {
    type: "text",
    name: "text-1632646974512-0",
    satir: "1",
    className: "row-12 form-control row-6 col-lg-6 row-8",
  },
];

const result = arr.map((o) => ({
  ...o,
  className: o.className.replace(/\s*row-\d+/g, "").trim(),
}));

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can also utilize regex pattern /\s*row-[^\s]+\s*/g

https://i.stack.imgur.com/gRaGG.png

const result = arr.map((o) => ({
  ...o,
  className: o.className.replace(/\s*row-[^\s]+\s*/g, " ").trim(),
}));

Answer №2

const information =[
  {
    type: "text",
    name: "text-1632646960432-0",
    line: "1",
    style: "form-control col-lg-3 row-1"
  },
  {
    type: "text",
    name: "text-1632646974512-0",
    line: "1",
    style: "form-control col-lg-6 row-8"
  }
];

const output = information.map((item) => {
  if (item.style.includes('row')) {
    return {
      ...item,
      style: item.style.replace(/row-[0-9]/, '').trim()
    }
  }
});

console.log(output);

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

I am having trouble displaying SASS styles in the browser after running webpack with node

In my current project for an online course, I am utilizing sass to style everything. The compilation process completes successfully without any errors, but unfortunately, the browser does not display any of the styles. The styles folder contains five file ...

Steps to dynamically display or conceal a DIV using Bootstrap 5

I am facing an issue with a navbar that has buttons to reveal hidden divs underneath. <a data-bs-toggle="offcanvas" href="#select" role="button" aria-controls="select"></a> <div id="select" c ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

Can you tell me what this code on Facebook is for?

Upon inspection of Facebook's activity in my browser, I stumbled upon the following code snippet: for (;;);{"t":"refresh"} Attempting to decipher its purpose reveals an infinite loop. Can you identify its function? ...

Dealing with substantial ajax responses using JavaScript

Currently, I am in the process of developing a website that utilizes jQuery File Tree. However, there is an issue with the enormous size of the AJAX response from the server - 900 KB and containing approximately 70,000 'files' (which are not actu ...

Create a "load additional data" button

I'm working on building my blog and I've run into a roadblock while trying to implement a load more button. Here's what I currently have: actions: { LOAD_ARTICLE_LIST: function ({ commit }) { axios.get('someurl/articles') ...

Obtain the text content in cases where the DOM is missing both the title and value fields

I am trying to extract the value from a text-box using selenium, but the text-box is marked as readonly and aria-live is set to off. Here is the DOM structure: <input autocomplete="off" class="abc" type="text" role="t ...

Retrieve an item fetched from the database using Javascript in MVC4 framework

How can I access the properties of an object returned from a database using JavaScript? This JavaScript function is invoked: function searchUser() { var userName = document.getElementById('UserName').value $.post("SearchForUser", { user ...

Identify the CSS class for the ionic component on the webpage

Currently, I am in the process of developing an application using ionic 2 and angular 2. Within this app, I am utilizing the ionic 2 component known as ModalController. Unfortunately, I have encountered a challenge when attempting to adjust the size of th ...

Failed to insert a new element into the MongoDB array

After trying the code below to update a document within a collection, I encountered an issue where a new item was not being added to an array in the script. Despite no exceptions being thrown, the array remained unchanged. I am seeking advice from experts ...

Utilizing threading within a while loop can lead to complications in the blinking of LEDs

I've been stuck on a technical issue for the past few days. Despite my efforts to find a solution by searching through online forums, I haven't been able to make any progress. The problem revolves around a program I'm working on that retrie ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

How MySQL handles empty variables when inserting data as null

I'm currently facing an issue while attempting to input data into a database from an external json URL in PHP. Some of the JSON data contains empty variables and I want to replace them with NULL or N/A if they are empty. Despite my attempts based on ...

Reactjs and Isotope offer the ability to expand and collapse on click. In this unique feature, only one item can be expanded at

Currently, I am working on refining an isotope application where each item expands upon clicking it and collapses when another item is clicked. However, the issue I am facing is that multiple cells can be opened simultaneously. I am looking for the most ef ...

Why does my computed property become undefined during unit testing of a head() method in Vue.js with Nuxt.js?

In my Vue.js + Nuxt.js component, I have implemented a head() method: <script> export default { name: 'my-page', head() { return { title: `${this.currentPage}` }; }, ... } </script> ...

What is the best way to respond to a hashchange event within AngularJs?

I am new to AngularJs and I am trying to update the page on hashchange events. Currently, I have this code which I know is not the proper way to do it: <!DOCTYPE html> <html> <head> <style> #hashdrop { display:block; ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

Is there a way to enable scrolling on the page upon loading, without moving the embedded PDF object itself?

After embedding a PDF object on my webpage, I noticed that when loading the page and scrolling using the mouse wheel, it actually scrolls up and down inside the PDF instead of moving through the entire page. To fix this issue, I have to first click in a bl ...