简体   繁体   中英

Replace keys in an array of objects in javascript

I want to replace the underscores in the object keys with spaces like USER_NAME to USER NAME. I tried the following but somehow it's not working.

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;

Link to JS Fiddle - https://jsfiddle.net/4ak6zjLd/3/

Could someone please let me know if I'm missing out on anything here?

You could use this ES6 function to apply a replacement on all object keys:

 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); 

If I understand correctly, you want to update the object keys inside the original link array.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM