For example I have an object:
{name:"Ken", address:"Sample", location:"Sample"}
How do I make the name, address and location in one code using javascript without using like name.toUpperCase()
.
For example I have an object:
{name:"Ken", address:"Sample", location:"Sample"}
How do I make the name, address and location in one code using javascript without using like name.toUpperCase()
.
You can use reduce()
on the Object.keys
. This method will not mutate the original object.
let obj = {name:"Ken", address:"Sample", location:"Sample"};
let result = Object.keys(obj).reduce((ac,k) => ({...ac,[k]:k.toUpperCase()}),{})
console.log(result)
Use for...in
and toUpperCase
like so:
const data = {
name: "Ken",
address: "Sample",
location: "Sample"
};
let upperCased = {};
for (var key in data) {
upperCased[key] = data[key].toUpperCase();
}
console.log(upperCased);
Why don't use a buildin method like toUpperCase() ?
If you dislike it you can wirtie your own method which check in a str every char, if it's value is in range 97-122 (a - z) then it subtract 32 transposing lowercase ASCII to uppercase ASCII (A - Z).
using buildin method seems more sane.
Here is a way to iterate trought dict and uppercase any of it's values
$tmp = {name:"Ken", address:"Sample", location:"Sample"}
$uppercase_tmp = {name: "", address: "", location: ""}
$keys = Object.keys($uppercase_tmp);
for($i = 0; $i < $keys.length; $i++) {
/* for each key in uppercase_tmp*/
$uppercase_tmp[$keys[$i]] = $tmp[$keys[$i]].toUpperCase()
}
Hoping it helps.
Hele
You could use a revival function of JSON.parse
and then check the type and if a string, check if the character is in a ... z
range, then subtract 32
from the character code to get an upper case letter.
const
uc = c => c >= 'a' && c <= 'z'
? String.fromCharCode(c.charCodeAt() - 32)
: c,
toUpperCase = (key, value) => typeof value === 'string'
? Array.from(value, uc).join('')
: value
var object = { name: "Ken", address: "Sample", location: "Sample" };
console.log(JSON.parse(JSON.stringify(object), toUpperCase));