0

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().

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Kenneth Bunyi
  • 23
  • 1
  • 4
  • You need to iterate over the properties of the object, and then update their values to uppercase. Tagging a duplicate of how to iterate over properties as you already know how to update them to uppercase. – Nisarg Shah Mar 07 '19 at 07:17
  • 2
    is it an assignment? – Nina Scholz Mar 07 '19 at 07:17
  • 1
    Possible duplicate of [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Nisarg Shah Mar 07 '19 at 07:17

4 Answers4

2

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

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);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

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

Hele
  • 189
  • 1
  • 12
0

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392