UPDATED INFORMATION:
To maintain the use of the same object but with updated key names, follow the approach of adding a new key and deleting the old key. For reference, please review the previous response if you intend to work with a new object.
var oldObject: any = {
first_name: 1,
last_name: 2
}
var keys = Object.keys(oldObject);
for(var key in oldObject)
{
let words = key.split("_");
oldObject[words[0][0].toLowerCase() + words[0].substring(1) + words[1][0].toUpperCase() + words[1].substring(1)] = oldObject[key]; // add new key
delete oldObject[key]; // delete old key
}
console.log(oldObject)
Ensure that the key names are unique and follow the word format {word1}_{word2}.
PREVIOUS RESPONSE:
Based on your query, it appears you want to change the keys of your object from something like first_name
to firstName
. While direct renaming is not possible, creating a new object with desired key names is an option.
If you already know the key names, you can easily create a new object:
var oldObject = {
first_name: 1,
last_name: 2
}
var newObject = {
firstName: oldObject.first_name,
lastName: oldObject.last_name
};
console.log(newObject)
If the key names follow the format {word1}_{word2}, without prior knowledge, custom logic is required. Here's a sample approach:
var oldObject: any = {
first_name: 1,
last_name: 2
}
var newObject: any = {};
var keys = Object.keys(oldObject);
for(var key in oldObject)
{
let words = key.split("_");
newObject[words[0][0].toLowerCase() + words[0].substring(1) + words[1][0].toUpperCase() + words[1].substring(1)] = oldObject[key];
}
console.log(newObject)
Access the playground for further exploration.