Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below

[
 {
   "subjectID": 1
   "Chosen" : "{subjectsChosen:Python,java,Angular}"
   "password": "{studentpw:123456abcd}"
 },
 {
   "subjectID": 2
   "Chosen" : "{subjectsChosen:SQL,Rprogram,React}"
   "password": "{studentpw:987654zyxwv}"
 }
]

We need to strip special characters and notations to achieve the following updated array using typescript

[
 {
   "subjectID": 1
   "Chosen" : "Python,java,Angular"
   "password": "23456abcd"
 },
 {
   "subjectID": 2
   "Chosen" : "SQL,Rprogram,React"
   "password": "987654zyxwv"
 }
]

Your assistance is greatly appreciated

Answer №1

give this a shot

for (let i = 0; i < subs.length; i++) {
  subs[i].Chosen = cleanUpSymbols(subs[i].Chosen);
  subs[i].password = cleanUpSymbols(subs[i].password);
}

function cleanUpSymbols(s: string) {
  return s.replace(/[\{\}]/g, "").split(":")[1];
}

outcome

[
  {
    "subjectID": 1,
    "Chosen": "Python,java,Angular",
    "password": "123456abcd"
  },
  {
    "subjectID": 2,
    "Chosen": "SQL,Rprogram,React",
    "password": "987654zyxwv"
  }
]

Answer №2

Welcome! Are the special characters in your object properties limited to '{', ':', '}'? If so, I have a solution for you that I have tested and it produces the expected results:

let items = [
    {
        itemID: 1,
        Chosen: "{itemsChosen:Apple,Banana,Orange}",
        price: "{itemprice:$2.99}"
    },
    {
        itemID: 2,
        Chosen: "{itemsChosen:Milk,Eggs,Bread}",
        price: "{itemprice:$3.49}"
    }
];

items.map((item) => {
    Object.keys(item).map(prop => {
        if (typeof item[prop] === 'string') {
            item[prop]=item[prop].replace(/[\{\}]/g, '').split(':')[1];
        }
    })
});

console.log(items);

You have the option to utilize any array operator method aside from forEach.

Answer №3

To manipulate each item, we can utilize the `map` operator of Array. By applying Regex and the `replace` method of string, we can transform the 'Chosen' and 'password' fields.

const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const myText = "{subjectsChosen:Python,java,Angular}";

myText.replace(re, '$1'); // Python,java,Angular

Here is the complete code snippet that performs the transformation on each item:

const items = [
 {
   "subjectID": 1,
   "Chosen" : "{subjectsChosen:Python,java,Angular}",
   "password": "{studentpw:123456abcd}"
 },
 {
   "subjectID": 2,
   "Chosen" : "{subjectsChosen:SQL,Rprogram,React}",
   "password": "{studentpw:987654zyxwv}"
 }
];

const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const passwordRegex = new RegExp(/\{studentpw:(.+)\}/, 'i')

const transformedItems = items.map(item => {
    return {
      ...item,
      "Chosen": item.Chosen.replace(chosenRegex, '$1'),
      "password": item.password.replace(passwordRegex, '$1')
    }
});

console.log(transformedItems);

If we prefer to have a single regex for both fields, we could use the following approach:

const transformRegex = new RegExp(/\{(.+):(.+)\}/, 'i');

....

return {
 ...item,
 "Chosen": item.Chosen.replace(transformRegex, '$2'), // Using $2 for the second group in the regex
 "password": item.password.replace(transformRegex, '$2')
}

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

Utilizing commonjs in Rollup configuration

Currently, I am tackling a project in Angular2. After going through the Angular2 aot documents, I successfully generated ngFactory files by utilizing rollup js as recommended. However, I encountered some npm packages that are non-es6. To load these non-es6 ...

Error: 'process' is not defined in this TypeScript environment

Encountering a typescript error while setting up a new project with express+ typescript - unable to find the name 'process'https://i.stack.imgur.com/gyIq0.png package.json "dependencies": { "express": "^4.16.4", "nodemon": "^1.18.7", ...

What are the best practices for utilizing the JQuery hasData() method effectively?

I have created a simple front-end web application where clicking a button triggers a GET Request to the Foursquare API, and then AJAX stores some of the response data into a div in the following manner: checkinsCount[i] = data.response.venues[i].stats.che ...

Android encountered an unknown error while trying to access the URL, resulting in an HTTP failure response with a status

My Ionic app runs perfectly fine on iOS, but when I try to run it on Android, I encounter the following error: Http failure response for (unknown url): 0 Unknown Error https://i.stack.imgur.com/8EFna.png I have CORS enabled on the server side and it wor ...

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...

A guide on incorporating a set of components to be utilized as custom HTML elements in Angular

I am in the process of revamping my application to be more modular on the UI side, with a focus on separating different elements including: App header Left navigation panel Main content on the right side of the nav panel I have successfully figured out ...

Performing an asynchronous Ajax call from a partial view in an Asp.net MVC application

Is it possible to use Ajax to fetch data from a form located in a partial view, send it to a controller, and receive a response message? Utilizing Ajax $("#submitContactInfo").on("click", function () { if ($('#contact-form').valid() === true) { ...

Tips for adding a value to a dictionary with nested dictionaries

I am currently working on a project where I need to convert Python scripts into JSON format. In order to achieve this, I am parsing the file and populating a dictionary with the necessary data. There are various tasks that require me to update this diction ...

What is the process for displaying node_modules directories in a json/javascript document?

Exploring ways to showcase the dependencies within my d3.js tree, I am curious if it's possible to dynamically list the dependencies' names in a JSON file or directly within the javascript file. I'm puzzled by how JavaScript can access folde ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

Utilize npm to compile TypeScript files as part of the npm build script execution

I am in the process of creating a build script using only npm, without relying on grunt or gulp. Most aspects are functioning well except for concatenating typescript files. While I can compile individual typescript files successfully, I am faced with th ...

Tips for modifying date format in Angular 8

My datepicker for a date column is displaying the incorrect date format after submission. I am looking to change this format to the correct one. I am working with bsConfig bootstrap in Angular 8, but I am unsure of how to modify the date format. The back ...

Switching between various conditions

Here is a sample of my component: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'myApp-component', templateUrl: './myApp.component.html', styleUrls: ['./myApp.component.scss'] }) ex ...

Unraveling Loops in Data Structures through Two-Step Deserialization

I am currently working with a Serializer/Deserializer that utilizes the PreserveReferencesHandling = PreserveReferencesHandling.All property. The challenge I am facing revolves around circular references within my code. Allow me to provide a simple examp ...

Resetting dynamic form changes in Vue.js explained

Currently, I am using a template like this: <div> <div v-for="(item, key) in items" :key="key"> <div> <input type="text" :value="item.title"> </div> ...

What is the best way to dynamically bind mysqli bind_param arguments in PHP?

My journey into using prepared and bound statements for my SQL queries has been quite enlightening. However, I have encountered a limitation in the current setup - it lacks flexibility when dealing with multiple parameters or scenarios where no parameter i ...

Sequelize is not giving the expected model even after utilizing `include: [{ model: this.buildModel, required: true }]`

I've hit a roadblock trying to solve this problem. Despite my belief that I've correctly handled the migration, model definition, and query, I'm unable to retrieve the build in my iteration. Below are the models: SequelizeBuildModel.ts @Ta ...

What causes the sudden change in value of this array?

I can't seem to figure out what's going on with this question. It might be something silly, but I haven't been able to find any clues. Here is the array in question: const superVillains = [ { value: '1', label: 'Thanos&apo ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

Finding the total of values within an array in Angular 2 and Ionic 2 by utilizing *ngfor

As I work on developing a mobile application using Ionic 2, my current task involves calculating the total allocation sum (Course.allocation) for each year per horse in the database. For instance: Table: Course (Race): [Id_course: 1, allocation: 200, dat ...