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 ?
4
Answers
You could simply use regex like this:
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, useObject.fromEntries
to convert the array of key-value pairs back to an object.You could create a reusable function that can prune keys of an object using a "prune" function i.e.
pruneFn
.You could even throw an error, if a key is illegal:
One more way with
Object.entries
andreduce