使用 javascript/underscore 编辑对象,如果尚不存在则添加新项目

Editing object with javascript/underscore, adding new items if don't exist already

所以我拉入了一个我想要 "edit" 的对象,在一些帮助下,我有一个函数可以找到我正在寻找的项目并替换值。我在构建它时没有考虑的是这些项目是否还不存在。

所以现在函数看起来像这样:

   myFunction = function(moduleName, stateName, startVar){
    //currentState brought in from factory controlling it
     var currentState = StateFactory.current();
    _.each(currentState, function(item) {
                if (item.module === moduleName) {
                  _.each(item.customUrl, function(innerItem) {
                    if (_.has(innerItem, stateName)) {
                      innerItem[stateName] = startVar;
                    }
                  });
                }
              });  
   }

所以 - 这在替换 startVar 值方面做得很好,假设它已经存在。我需要添加一些级别的检查以确保项目存在(如果他们不添加它们)。

因此,作为参考,这就是 currentState 的样子

 [{
 "module": "module1",
 "customUrl": [
    { "mod1": "2" },
    { "mod2": "1" }
]
 }, {
"module": "module2",
"customUrl": [
    { "mod3": "false" },
    { "mod4": "5" }
]
 }
 ];

所以如果我通过了

 myFunction("module1","mod1",3);

这很好用,但是如果我通过

myFunction("module5","mod8","false");

或者介于两者之间,例如

 myFunction("module1","mod30","false");

这个函数不会处理那个场景。我可以使用一些帮助来解决这个问题。另外,我正在使用下划线(如果需要帮助的话)。感谢您抽空阅读!

正如 Phari 所提到的那样 - 大意是

  currentState[moduleName].customUrl[stateName] = startVar;

我原以为我可以只创建对象 _.extend,但因为它是一个对象数组,无法正常工作。

我的意思是:

  var tempOb = {"module" : moduleName, "customUrl" : [{stateName : startVar}]};

  _.extend(currentState, tempOb);

不太适合对象数组。

看来你需要做的就是删除if语句:

                if (_.has(innerItem, stateName)) {
                  innerItem[stateName] = startVar;
                }

应该变得简单:

                  innerItem[stateName] = startVar;

然后如果 属性 不存在,它将被添加。如果它已经存在,它将被覆盖。

编辑:处理高层缺席:

myFunction = function(moduleName, stateName, startVar){
//currentState brought in from factory controlling it
 var currentState = StateFactory.current();
 var found = false;
_.each(currentState, function(item) {
            if (item.module === moduleName) {
              found = true;
              _.each(item.customUrl, function(innerItem) {
                if (_.has(innerItem, stateName)) {
                  innerItem[stateName] = startVar;
                }
              });
            }
          });  
    if ( ! found ) {
        var newItem = {
            module: moduleName,
            customUrl: []
        };
        var newInnerItem = {};
        newInnerItem[stateName] = startVar;
        newItem.customUrl.push(newInnerItem);
        currentState.push(newItem);
    }
}