Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to uppercase Javascript object keys?

Anyone know a good way to turn this?:

var obj = [{key1: value1,key2: value2},{key3: value3,key4: value4}];

into:

var obj = [{Key1: value1,Key2: value2},{Key3: value3,Key4: value4}];
like image 978
Brandon Minton Avatar asked Sep 13 '11 21:09

Brandon Minton


People also ask

Can objects be keys in JavaScript?

Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.

Are JavaScript keys case sensitive?

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.


1 Answers

As of 2019 you can use Object.fromEntries:

let populations = {london: 8.9, beijing: 21.54, mumbai: 18.41};  // March 2020

let entries = Object.entries(populations);
let capsEntries = entries.map((entry) => [entry[0][0].toUpperCase() + entry[0].slice(1), entry[1]]);
let capsPopulations = Object.fromEntries(capsEntries);

console.log(capsPopulations);
like image 106
Jeremiah England Avatar answered Oct 15 '22 11:10

Jeremiah England