简体   繁体   English

使用数组符号将javascript中的值分配给子对象字段

[英]assigning value in javascript to sub-object field using array notation

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. 如果nameOfField只是字段名称,则可以使用。

However, if I define in $scope object "subObject": 但是,如果我在$ scope对象中定义“ 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. 但是,我确实需要对子对象字段使用nameOfField方法,并感谢如何使它起作用的提示。 I can not predict if subObject will be featured in nameOfField - it can be both name field and subObject.someSubField. 我无法预测subObject是否将出现在nameOfField中-它既可以是name字段,又可以是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. 编辑:与问题的不同之处在于使用字符串键访问嵌套的JavaScript对象是我不仅需要访问对象的值,还需要对其进行修改。

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): 这里是一个示例(显然,必须扩展它以支持仅2个级别的更多级别):

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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM