Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Replace keys within an array of objects

I have an array of objects as below

[
    {contactTypeField-0: 'Index0', firstNameField-0: '0', uniqueRowField-0: 0},
    {contactTypeField-1: 'Index1', firstNameField-1: '1', uniqueRowField-1: 0}
]

What is the best way to replace the keys i.e. I want to remove -0, -1, -2 from each of the keys. So I am expecting the output as

[
    {contactTypeField: 'Index0', firstNameField: '0', uniqueRowField: 0},
    {contactTypeField: 'Index1', firstNameField: '1', uniqueRowField: 0}
]

Is there some ES6 way to achieve this ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Array#map to transform the array of objects to a new array.

For each object, map over its entries and use String#replace to remove the required suffix (the regular expression -\d+$ matches a hyphen and one or more consecutive digits directly preceding the end of the string). Finally, use Object.fromEntries to convert the array of key-value pairs back to an object.

const arr=[{"contactTypeField-0":"Index0","firstNameField-0":"0","uniqueRowField-0":0},{"contactTypeField-1":"Index1","firstNameField-1":"1","uniqueRowField-1":0}];
const res = arr.map(o => Object.fromEntries(Object.entries(o)
                .map(([k, v]) => [k.replace(/-\d+$/, ''), v])));
console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading