Reputation: 2599
I have a javascript Array with multiple objects.
var array = [{First_name:Mike, Last_Name: Kelly},{First_Name:Charles, Last_Name:Bronson},{First_Name:Chuck, Last_Name:Norris}];
How can i iterate through each object and string.replace('_'g,' ') each key? Essentially i need to replace the underscore with spaces.
Upvotes: 0
Views: 1970
Reputation: 59367
var array = [
{First_Name: 'Mike', Last_Name: 'Kelly'},
{First_Name: 'Charles', Last_Name: 'Bronson'},
{First_Name: 'Chuck', Last_Name: 'Norris'},
];
function convert(obj) {
const result = {};
Object.keys(obj).forEach(function (key) {
result[key.replace(/_/g, ' ')] = obj[key];
});
return result;
}
var result = array.map(function (o) {
return convert(o);
});
console.log(result);
Upvotes: 1
Reputation: 16068
for (var i = 0; i < array.length; i++) {
for (var prop in array[i]) {
if (prop.includes("_")) {
array[i][prop.split("_").join(" ")] = array[i][prop];
delete array[i][prop];
}
}
}
Upvotes: 3