在javascript中替换对象数组中的键

时间:2016-09-03 13:46:55

标签: javascript

我想用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/

如果我在这里错过了什么,有人可以告诉我吗?

2 个答案:

答案 0 :(得分:3)

您可以使用此ES6函数对所有对象键应用替换:

&#13;
&#13;
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;
&#13;
&#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);

https://jsfiddle.net/4ak6zjLd/5/