Replace string values with an object array for a particular property

When faced with the task of replacing specific string values defined by the user in an array of objects, but only applying the rules to certain properties, there is a need for a more efficient approach. For instance, consider the array below:

[
{Name: 'Name1 Address', Fullname: 'Fullname1', Address: 'Address1'},
{Name: 'Name2', Fullname: 'Fullname2', Address: 'Address2'},
{Name: 'Name3', Fullname: 'Fullname3', Address: 'Address3'}
]

If the user wishes to substitute the word 'address' with 'test' exclusively within the 'Name' property, the updated array would appear as follows:

[
{Name: 'Name1 test', Fullname: 'Fullname1', Address: 'Address1'},
{Name: 'Name2', Fullname: 'Fullname2', Address: 'Address2'},
{Name: 'Name3', Fullname: 'Fullname3', Address: 'Address3'}
]

Given the potential for numerous objects within the array and various user-defined substitution rules, methods are needed to streamline this process without requiring manual replacement on each item for a specific property.

Answer №1

Uncertain if a specific type or function is required for this task, so here are examples of both:

const data = [
    { Name: 'Name1 Address', Fullname: 'Fullname1', Address: 'Address1' },
    { Name: 'Name2', Fullname: 'Fullname2', Address: 'Address2' },
    { Name: 'Name3', Fullname: 'Fullname3', Address: 'Address3' },
] as const;

// Modifying types
type UpdatedAddress<T extends typeof data> = [
    ...{
        [K in keyof T]: {
            // Assuming all "Name" properties follow a similar format.
            Name: T[K]['Name'] extends `Name${infer I} Address` ? `Name${I} test` : T[K]['Name'];
            Fullname: T[K]['Fullname'];
            Address: T[K]['Address'];
        };
    }
];

let b: UpdatedAddress<typeof data>;

// Actual modification
const updateAddress = <T extends typeof data>(entries: T) => {
    return entries.map((entry) => ({
        ...entry,
        Name: entry.Name.replace(/Address/g, 'test'),
    })) as UpdatedAddress<T>;
};

console.log(updateAddress(data));

Compiled:

"use strict";
const data = [
    { Name: 'Name1 Address', Fullname: 'Fullname1', Address: 'Address1' },
    { Name: 'Name2', Fullname: 'Fullname2', Address: 'Address2' },
    { Name: 'Name3', Fullname: 'Fullname3', Address: 'Address3' },
];
let b;
const updateAddress = (entries) => {
    return entries.map((entry) => ({
        ...entry,
        Name: entry.Name.replace(/Address/g, 'test'),
    }));
};
console.log(updateAddress(data));

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

Shared validation between two input fields in Angular 2+

I have a unique task at hand. I am working on creating an input field with shared validation. The goal is to ensure that both fields are technically required, but if a user fills in their email address, then both fields become valid. Similarly, if they ent ...

Encountering overload error with Vue 3 and Axios integration

Currently utilizing Vue 3, Vite, Axios, and TypeScript. While my function functions properly in development, it throws an error in my IDE and during the build process. get count() { axios({ method: "get", url: "/info/count", h ...

Generating a dynamic table using Angular

My goal is to populate a table dynamically using the code below: teams.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { TeamService } from 'src/app/services/team.ser ...

Promise rejection not handled: The play() function was unsuccessful as it requires the user to interact with the document beforehand

After upgrading my application from Angular 10 to 11, I encountered an error while running unit tests. The error causes the tests to terminate, but strangely, sometimes they run without any issues. Does anyone have suggestions on how to resolve this issue? ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...

Encountering a challenge when upgrading to eslint version 9.0.0

Encountering an issue while trying to upgrade eslint to version 9.0.0. ⋊> ~/A/fusion on turborepo ⨯ bun lint 22:21:58 $ eslint packages/*/src/**/* Oops! Something went wrong! :( ESLint: 9.0. ...

Can you explain the significance of the symbol ! when declaring a variable in TypeScript?

Currently, I am delving into an Angular project and came across a peculiar line of code in the component.ts file provided by my instructor. @Input() public searchType!: string; This line resides within the OnInit() function of the component's TypeScr ...

Retrieve the total number of hours within a designated time frame that falls within a different time frame

Having a difficult time with this, let me present you with a scenario: A waiter at a restaurant earns $15/hour, but between 9:00 PM and 2:30 AM, he gets paid an additional $3/hour. I have the 'start' and 'end' of the shift as Date obje ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

Tips for incorporating moment.js library into an Angular 2 TypeScript application

I attempted to utilize TypeScript bindings in my project: npm install moment --save typings install moment --ambient -- save test.ts file content: import {moment} from 'moment/moment'; I also tried without using TypeScript bindings: npm inst ...

Issue with Validators in Model-driven Forms

Currently conducting testing on a basic application. These are the files in use: home.component.ts import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; @Componen ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

Error encountered while attempting to resume activity: TypeError - the function `callResume` is not defined in NativeScript Angular 2

When the resume event occurs, I must invoke the method this.callResume(). However, upon calling the method, a runtime error is thrown: TypeError: this.callResume is not a function I am uncertain about how to call a method from within the resume method ...

Differentiate the array type within an object in TypeScript

I understand how to specify the type for a variable. let members: string[] = [] // this example works flawlessly My goal is to have an array of strings within an object. How can I structure it correctly? const team = { name: String, members<st ...

What is the correct location to import a custom theme in MUI for Next.js?

I am currently working on a React/Next.js project and I need to customize the colors using MUI. After discovering createTheme(), I realized that the project is written in Typescript. Should I create a separate file with the following code? And where shou ...

What factors should I consider when determining whether to include @types/* in the `dependencies` or `devDependencies` section?

Currently using TypeScript 2 in my project, I am looking to incorporate a JavaScript library along with its typings. While I know I can easily install the types using npm install @types/some-library, I am uncertain whether to use --save or --save-dev. The ...

Utilizing objects as values with `react-hook-form`

About the Issue I'm facing an issue with a component that utilizes an object as its value. My goal is to integrate this component with react-hook-form The challenge arises when react-hook-form considers my object as a nested form control Background ...

Issue with Click event not working on dynamically added button in Angular 8

My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below ...