1

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;
JiniKJohny
  • 1,172
  • 13
  • 29

1 Answers1

1

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;
Community
  • 1
  • 1
Manish Kr. Shukla
  • 4,447
  • 1
  • 20
  • 35
  • it's called Bracket Notation; even though it uses the same characters `[ ]` it does not imply that the data is an Array. – Claies Sep 16 '15 at 04:22
  • Well, i didn't said that it's an array.. Since the approach of accessing the data is quite similar to Arrays, the terminology is so.. – Manish Kr. Shukla Sep 16 '15 at 04:30
  • OP can even use `$scope.mainObject["key1.arrayLst[]"]` ie square bracket notation – Vineet Sep 16 '15 at 04:33
  • @ManishKr.Shukla In my opinion OP has already been declared `arrayLst` as an array so you should suggest him to `push` the data in `arrayLst`. – Vineet Sep 16 '15 at 04:34
  • @ManishKr.Shukla no, the exact opposite is true. The terminology is "Bracket Notation", or "Square Bracket Notation" specifically to ensure that there is no confusion with the Array data structure. The article you linked to even refers to it as Square Bracket Notation. just by using the word Array in your question, you introduced a suggested comment that doesn't even really make sense about how to manage arrays. – Claies Sep 16 '15 at 04:39