2017-06-22 52 views
-1

我有一個具有多個對象的javascript數組。用數組中的每個對象鍵的空格替換下劃線

var array = [{First_name:Mike, Last_Name: Kelly},{First_Name:Charles, Last_Name:Bronson},{First_Name:Chuck, Last_Name:Norris}]; 

如何迭代每個對象和string.replace('_'g,'')每個鍵? 本質上我需要用空格替換下劃線。

回答

1

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

3
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]; 
     } 
    } 
}