Search code examples
angularjsangular-ngmodel

Angular JS : using dynamic object names from list of Objects


Is there any way to read an object from a list of objects dynamically with object key. My complex objects is something like :

$scope.mainObject = {
   name : "Some value",
   desc : "Some desc",
   key1: {
      arrayLst: []
   },
   key2: {
      arrayLst: []
   }
}

In my method, I have the key value either key1 or key2 in a string keyValue. How can I write to object like :

$scope.mainObject.key1.arrayLst = data;

In the form of something like :

$scope.mainObject.get(keyValue).arrayLst = data;

Solution

  • Well, there's something known as Array notation in JavaScript objects. More on it here.

    You can write it something like this :

    $scope.mainObject.[keyValue].arrayLst = data;