0

I want to create dynamic variables like Vikas0, Vikas1, Vikas2, Vikas3 and so on.

$.each(data, function(key, value){
  $scope.servicesDataList[key].list="Vikas"+key;
  // will print Vikas0, Vikas1, Vikas2, Vikas3
  console.log($scope.servicesDataList[key].list); 
});

Now I want to create dynamic variables. Will any one knows how can I achieve this. I hope I am able to elaborate my question.

3
  • you cannot create an independent dynamic variable but can create a hash map instead as var hashValue and then use hashValue[$scope.servicesDataList[key].list] = "value" Commented Jan 31, 2017 at 5:22
  • Why not use an array? Commented Jan 31, 2017 at 5:32
  • I got a result in json, that's why not using array Commented Jan 31, 2017 at 5:35

2 Answers 2

1
You can use.
 the syntax would be = $scope["vikas"+key] = []

    $.each(data, function(key, value){    
       $scope["Vikas"+key] = value;    
       console.log($scope["vikas"+key].value);
     will print Vikas0, Vikas1,Vikas2, Vikas3  

});
Sign up to request clarification or add additional context in comments.

2 Comments

So it will create Vikas0 variable with the value Vikas0
and it can hold any value like array, JSON, string or any
0

You can with using array of object act as a dynamic variable.

             Var conctVar="":
              $.each(data, function(key, value){
                conctVar= conctVar + "{Vikas"+key + ":Vikas"+value+"},";
               });

               conctVar=conctVar.slice(0,-1);
               $scope.FinalObject=JSON.parse(conctVar);// now the string will convert to a array object

Now you can get the array object looks like below

$scope.FinalObject.Vikas1,// value is vikas1

$scope.FinalObject.Vikas2,// value is vikas2

$scope.FinalObject.Vikas3,//value is vikas3

$scope.FinalObject.Vikas4//value is vikas4

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.