-1

I have a program and want to change the object key names in a JSON file with a function. I have already created a function that changes the keys when it is displayed via Angular, but I want to create a function that allows me to change the object key names directly in the JSON file.

Here is a sample of my JSON file ( the actual array contains over 300 entries ):

[
    {
        "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":""
    }
]

and what I have done thus far to change the key names:

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

Thank you for all of your help :) !

JAAulde
  • 19,250
  • 5
  • 52
  • 63
Kate S
  • 318
  • 4
  • 14

1 Answers1

0

Maybe this should help you:

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);
});
Arnaud Gueras
  • 2,014
  • 11
  • 14