1

I want to set key names of the Object dynamic. Here is my code:-

if (fieldName == 'DEPARTMENT') {
   var objCombos = []; 
   objCombos = $scope.getValues ('DEPARTMENT');
}
if (fieldName == 'DESIG') {
   var objCombos = []; 
   objCombos = $scope.getValues ('DESIG');
}

$scope.getValues = function (fieldName) {            
        var objDepart= [];
        jq.ajax({
            type: "GET",
            url: "/Data/getValuesWithId?fieldName=" + fieldName,
            async: false,
            success: function (result) {
                angular.forEach(result, function (value, key) {                                               
                   objDepart.push({ id: key, fieldName: value });
                   // This is what i expect { 'id' : 11, 'DEPARTMENT': value }
                   // The key of 2nd element is dynamic(DEPARTMENT, DESIG, etc)
                });
            }
        });
        return objDepart;
    }

How to set keys dynamically?

1 Answer 1

6

Use Bracket notation

 var obj = { id: key};
 obj[fieldName] = value; //Use Bracket notation
 objDepart.push(obj);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.