2015-11-24 100 views
-1

我有一個程序,並希望通過函數更改JSON文件中的對象鍵名稱。我已經創建了一個函數,它可以在通過Angular顯示時更改這些鍵,但是我想創建一個函數,允許我直接在JSON文件中更改對象鍵名稱。使用函數重寫JSON對象鍵?

這裏是我的JSON文件的樣本(實際陣列包含超過300項):

[ 
    { 
     "FIELD1":"key", 
     "FIELD2":"company", 
     "FIELD3":"team", 
     "FIELD4":"num_female_eng", 
     "FIELD5":"num_eng", 
     "FIELD6":"percent_female_eng", 
     "FIELD7":"last_updated", 
     "FIELD8":"Submit more data!", 
     "FIELD9":"https://github.com/triketora/women-in-software-eng" 
    }, 
    { 
     "FIELD1":"all", 
     "FIELD2":"ALL", 
     "FIELD3":"N/A", 
     "FIELD4":"2798", 
     "FIELD5":"14810", 
     "FIELD6":"18.89", 
     "FIELD7":"11/18/2015", 
     "FIELD8":"", 
     "FIELD9":"" 
    }, 
    { 
     "FIELD1":"wellsfargo", 
     "FIELD2":"Wells Fargo", 
     "FIELD3":"N/A", 
     "FIELD4":"1296", 
     "FIELD5":"5407", 
     "FIELD6":"23.97", 
     "FIELD7":"7/22/2015", 
     "FIELD8":"", 
     "FIELD9":"" 
    } 
] 

什麼迄今爲止我所做的更改密鑰名稱:

(function() { 
    'use strict'; 
    angular 
    .module("app.companies") 
    .controller('CompaniesCtrl', CompaniesCtrl); 

    CompaniesCtrl.$inject = ['$scope', 'CompanyFactory']; 

    function CompaniesCtrl($scope, CompanyFactory) { 
     $scope.work = "i work"; 
     $scope.companies = CompanyFactory; 

     $scope.makeChart = function(company){ 
     $scope.femaleDevs = parseInt(company.num_female_eng); 
     $scope.allDevs = parseInt(company.num_eng); 
     $scope.company = company.company; 
     $scope.maleDevs = $scope.allDevs - $scope.femaleDevs; 
     console.log($scope.maleDevs); 
     }; 
    } 
})(); 

謝謝你的所有幫助:)!

+2

你的問題中不包含的問題。 – zerkms

+0

您想要更改JSON文件的內容,並且您向我們提供了一個Angular Code。您想在代碼中將「FIELDX」名稱更改爲正常名稱? –

+0

請參閱http://stackoverflow.com/questions/4647817/javascript-object-rename-key。 –

回答

0

也許這會幫助你:

var fieldsmap = { 
    'FIELD1': 'key', 
    'FIELD2': 'company', 
    'FIELD3': 'team', 
    'FIELD4': 'num_female_eng', 
    'FIELD5': 'num_eng', 
    'FIELD6': 'percent_female_eng', 
    'FIELD7': 'last_updated', 
    'FIELD8': 'name2', 
    'FIELD9': 'name3' 
}; 

function renameObjectKeys(obj) { 
    for (var key in fieldsmap) { 
     if (obj.hasOwnProperty(key) && fieldsmap.hasOwnProperty(key)) { 
      obj[fieldsmap[key]] = obj[key]; //copy the key into new key 
      delete(obj[key]); // delete old key 
     } 
    } 
} 

myArray.forEach(function(object) { 
    renameObjectKeys(object); 
});