Use regex to rename keys of array of objects

  • A+
Category:Languages

I have an array of objects. Each object has a lot of keys (more than 100) and some of these keys can have special chars that I would like to remove.

I try to do what I want in this way:

const result = data.map(datum => {   const keys = Object.keys(datum)   const replacedKeys = keys.map(key => {     const newKey = key.replace(/[.|&;$%@%"<>+]/g, '')   })   // ?? }) 

But I'm sure it's not the right way..

 


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] })) )); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: