Reputation: 16
I have an object to convert marks to uppearcase()
const doc = {
name: 'Hong Kong',
topLevelDomain: '.hk',
alpha2Code: 'HK',
}
let newDoc = JSON.stringify(doc)
let upperCased = {};
for (let i = 0; i >= 0; i++) {
upperCased = newDoc[i].toUpperCase();
}
console.log(upperCased)
I try to covert doc
to string at first.
Then, i use for-loop to uppercase newDoc
I need to convert like this
Name: Hong Kong
TopLevelDomain: .hk
Alpha2Code: HK
How can I do that?
Upvotes: 0
Views: 58
Reputation: 23838
Run through all properties and replace the first character of each property.
const doc = {
name: 'Hong Kong',
topLevelDomain: '.hk',
alpha2Code: 'HK',
}
Object.keys(doc).forEach(key => {
//Save the value and delete the property
let val = doc[key];
delete doc[key];
//Create a new property with upper cased first letter
key = key.replace(/./g, (c, i) => i == 0? key[0].toUpperCase(): c);
doc[key] = val;
})
console.log(doc);
Upvotes: 0
Reputation: 5308
You can make use of Object.fromEntries
to create the object from key value pair by taking Object.entries
. Here is an working example:
const doc = { name: 'Hong Kong', topLevelDomain: '.hk',alpha2Code: 'HK'};
var result = Object.fromEntries(Object.entries(doc).map(([key, value])=>[key[0].toUpperCase()+key.slice(1), value]));
console.log(result);
Upvotes: 1