1

I have an intention to set a field value of an object like this

 $scope[nameOfField]=value;

which works if nameOfField is just field name.

However, if I define in $scope object "subObject":

$scope.subObject={};
var nameOfField='subObject.someSubField';

$scope[nameOfField]=12345;

this does not work. Apparently I can not address directly sub-object fields like this. I however do need to use nameOfField approach with sub-object fields, and appreciate hints how to make it work. I can not predict if subObject will be featured in nameOfField - it can be both name field and subObject.someSubField.

EDIT: Difference with the question Accessing nested JavaScript objects with string key is that I not only need to access value of object but modify it.

Community
  • 1
  • 1
onkami
  • 8,791
  • 17
  • 90
  • 176
  • possible duplicate of [Accessing nested JavaScript objects with string key](http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Siguza Jun 03 '15 at 12:54
  • @Siguza right direction, can Read value, but how I Assign value to an object field specified in string? – onkami Jun 03 '15 at 13:21

1 Answers1

1

Well your current code would result into

$scope['subObject.someSubField']=12345;

which would be a syntax error. Correct would be

$scope[nameOfField1][nameOfField2]=12345;

So you need a function to archieve this. Here an example (obviously this has to be extended to support more then just the 2 levels):

var scope = {};
function setValue(scopeString, val){
    var match = /(\w+)\.(\w+)/.exec(scopeString);
    if(!scope[match[1]]) //create if needed
      scope[match[1]] = {};
    scope[match[1]][match[2]] = val;
}
function getValue(scopeString){
    var match = /(\w+)\.(\w+)/.exec(scopeString);
    return scope[match[1]][match[2]];
}
setValue('lvl1.lvl2', 1);
console.log(getValue('lvl1.lvl2'));
Tom
  • 195
  • 9
  • `$scope['subObject.someSubField']=12345;` is certainly **not** a syntax error. It just does something different. – Siguza Jun 03 '15 at 13:31