任何人都知道转这个的好方法吗?:
var obj = [{key1: value1,key2: value2},{key3: value3,key4: value4}];
成:
var obj = [{Key1: value1,Key2: value2},{Key3: value3,Key4: value4}];
答案 0 :(得分:14)
循环删除并替换:
var obj = [{key1: 1,key2: 1},{key3: 1,key4: 1}];
for(var i = 0; i<obj.length;i++) {
var a = obj[i];
for (var key in a) {
var temp;
if (a.hasOwnProperty(key)) {
temp = a[key];
delete a[key];
a[key.charAt(0).toUpperCase() + key.substring(1)] = temp;
}
}
obj[i] = a;
}
答案 1 :(得分:4)
从2019年开始,您可以使用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);
答案 2 :(得分:0)
implementation 'pull-parser:pull-parser:2.1.10'
答案 3 :(得分:0)
如果您只需要大写首字母,您可以使用 Jeremiah's answer
或者如果您需要将每个单词的首字母大写,请考虑以下内容
let populations = {"london": 8.9, "beijing": 21.54, "mumbai": 18.41, "new york": 19.4};
let entries = Object.entries(populations);
// Capitalize first letter of each word
let capsEntries = entries.map((entry) => [entry[0].replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase()), entry[1]]);
let capsPopulations = Object.fromEntries(capsEntries);
console.log(capsPopulations)
从 this answer 中采用的正则表达式
正则表达式解释:
(^\w{1})
:匹配字符串的第一个字符|
:或(\s{1}\w{1})
:匹配一个空格后的字符g
:匹配所有答案 4 :(得分:0)
另一种方法(更干净)
import * as _ from 'lodash';
function capitalizeObjectKeys(obj) { 返回 _.transform(obj, (result, val, key) => { 结果[key.charAt(0).toUpperCase() + key.slice(1)] = val; }); }
答案 5 :(得分:-3)
使用lodash的_.capitalize函数
_.capitalize('firstName') => FirstName