Use regex to rename keys of array of objects
You could map new object with a new key and create a single object with Object.assign
.
const result = data.map(datum => Object.assign(...Object
.keys(datum)
.map(key => ({ [key.replace(/[.|&;$%@%"<>+]/g, '')]: datum[key] }))
));
With the ES8 Object.fromEntries
method that has already found its way in FireFox, you can do:
const sanitiseKeys = o => Object.fromEntries(Object.entries(o).map(([k,v]) =>
[k.replace(/[.|&;$%@%"<>+]/g,""), v]));
// Example use:
var data = [{ "name#": "John" }, { "@key": 2 }];
data = data.map(sanitiseKeys);
console.log(data);
If not yet implemented, here is a polyfill:
Object.fromEntries = arr => Object.assign({}, ...arr.map( ([k, v]) => ({[k]: v}) ));