Object array replace string values for specific property

Viewed 30

I need to replace some string values the user defines for an array of objects, but apply the rules only for some of the properties. For example if I have the following array:

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

and the user wants to replace the word 'address' with 'test' but only for the 'Name' property, then the array should look like this:

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

Since the array can contain a lot of objects and the user can add rules for whatever property they want, how can I replace these values without having to go through each item and use string replace for a specific property?

1 Answers

Not sure if you need a type that does this, or if you need a function that does this, so here's both:

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

// Replacing it within the types
type ReplacedAddress<T extends typeof x> = [
    ...{
        [K in keyof T]: {
            // This assumes that all the "Name" properties follow the same 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 a: ReplacedAddress<typeof x>;

// Actually replacing it
const replaceAddress = <T extends typeof x>(items: T) => {
    return items.map((item) => ({
        ...item,
        Name: item.Name.replace(/Address/g, 'test'),
    })) as ReplacedAddress<T>;
};

console.log(replaceAddress(x));

Compiled:

"use strict";
const x = [
    { Name: 'Name1 Address', Fullname: 'Fullname1', Address: 'Address1' },
    { Name: 'Name2', Fullname: 'Fullname2', Address: 'Address2' },
    { Name: 'Name3', Fullname: 'Fullname3', Address: 'Address3' },
];
let a;
const replaceAddress = (items) => {
    return items.map((item) => ({
        ...item,
        Name: item.Name.replace(/Address/g, 'test'),
    }));
};
console.log(replaceAddress(x));

Related