Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lowercase JavaScript object values

I have an array of JavaScript objects:

var obj = [{key1: Value1, key2: VALUE2},{key1: Value1, key2: VALUE2}];

I want the value of the key2 to be in lowercase, like this:

var obj = [{key1: Value1, key2: value2},{key1: Value1, key2: value2}];

How can I change the value from lowercase to uppercase?

like image 435
monda Avatar asked Sep 26 '26 21:09

monda


1 Answers

If I understand your question correctly, you want to change the value of each object's key2 property, to be a lowercase string (I'm assuming they're strings).

You can do this with a simple map.

obj = obj.map(function(a) {
    a.key2 = a.key2.toLowerCase();
    return a;
});

There are some differences in all the answers given here, surrounding object references. In my answer above, the array itself will be a new reference, but the objects inside will remain as the same reference. To clarify this by way of example

var mapped = obj.map(function(a) {
    a.key2 = a.key2.toLowerCase();
    return a;
});

console.log(obj === mapped) // false
console.log(obj[0] === mapped[0]) // true

If you're using a for loop or a forEach array function, then the array reference will remain the same.

See this fiddle for reference.

like image 152
James Hay Avatar answered Sep 29 '26 12:09

James Hay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!