我想用USER_NAME和USER NAME之类的空格替换对象键中的下划线。我尝试了以下但不知道它不起作用。
var link = [{
"USER_NAME": "abc",
"USER_DOB": "10/25/1985",
}, {
"USER_NAME": "xyz",
"USER_DOB": "10/25/1986"
}];
var html = '';
for (var i = 0; i < link.length; i++) {
var tableHeaders = Object.keys(link[i]);
for (var j = 0; j < tableHeaders.length; j++) {
var formattedStr = tableHeaders[j].replace(/_/g, ' ');
Object.keys(link[i])[j] = formattedStr;
html += Object.keys(link[i])[j] + ' -- ' + formattedStr + '<br /><br />';
}
}
document.getElementById('test').innerHTML = html;
链接到JS小提琴 - https://jsfiddle.net/4ak6zjLd/3/
如果我在这里错过了什么,有人可以告诉我吗?
答案 0 :(得分:3)
您可以使用此ES6函数对所有对象键应用替换:
function replaceKeys(obj, find, replace) {
return Object.keys(obj).reduce (
(acc, key) => Object.assign(acc, { [key.replace(find, replace)]: obj[key] }), {});
}
// sample data
var link = [{
"USER_NAME": "abc",
"USER_DOB": "10/25/1985",
}, {
"USER_NAME": "xyz",
"USER_DOB": "10/25/1986"
}];
// replace the underscores in each of the objects
link = link.map(obj => replaceKeys(obj, /_/g, ' '));
// output result
console.log(link);
&#13;
答案 1 :(得分:0)
如果我理解正确,您希望更新原始link
数组中的对象键。
var link = [{
"USER_NAME": "abc",
"USER_DOB": "10/25/1985",
}, {
"USER_NAME": "xyz",
"USER_DOB": "10/25/1986"
}];
for (var i = 0; i < link.length; i++) {
var tableHeaders = Object.keys(link[i]);
// We create a fresh link object that will have formatted keys:
var newLink = {};
for (var j = 0; j < tableHeaders.length; j++) {
var badKey = tableHeaders[j];
var goodKey = badKey.replace(/_/g, ' ');
newLink[goodKey] = link[i][badKey];
}
// Now we replace the original link item with the new one:
link[i] = newLink;
}
document.getElementById('test').innerHTML = JSON.stringify(link);