-2

If I have the following object, how can I redefine the keys to remove the prefix "Class"?

{ 
    ClassName: "John",
    ClassEmail: "john@doe.com",
    ClassPhone: "1234567"
}

so it becomes

{ 
    Name: "John",
    Email: "john@doe.com",
    Phone: "1234567"
}

Is there any easy way?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rjpedrosa
  • 652
  • 2
  • 7
  • 10
  • Are you able to please show what you've tried and what isn't working with your attempt? – Nick Parsons Dec 21 '22 at 10:16
  • You can use this answer from the dupe [JavaScript: Object Rename Key](https://stackoverflow.com/a/58974459) but use `.replaceAll()` for the key (or `.replace()` with a global regular expression) – Nick Parsons Dec 21 '22 at 10:18

1 Answers1

0

const obj = {
  ClassName: "John",
  ClassEmail: "john@doe.com",
  ClassPhone: "1234567"
}

const newObj = Object.entries(obj).reduce((acc, item) => ({ ...acc,
  [item[0].replace(/Class/g, "")]: item[1]
}), {})

console.log(newObj)
Jay
  • 2,826
  • 2
  • 13
  • 28