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 ?
>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);