下划线,查找和更改对象中的值

Underscore, find and change value in object

我正在尝试查找并替换对象中函数中的值

我的对象看起来像这样:

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

我的函数是这样的:

 myFunction = function(mod, name, replace){
 //replace item in testStates

}

基本上我想做的是使用这些变量在内部搜索 mod 是 "module" 值,名称是 "mod" 的键(如 mod1 or mod2 in the exampels), replace 是要在所选 mod.

上替换的值

所以如果我说

 myfunction(module1, mod1, 5);

然后我希望对象看起来像

    var testStates = [{
    "module": "module1",
    "customUrl": [
        { "mod1": "5" },   ////Changed
        { "mod2": "1" }
    ]
}, {
    "module": "module2",
    "customUrl": [
        { "mod3": "false" },
        { "mod4": "5" }
    ]
}
];

有点像对对象的查找和替换。我不确定如何用下划线解决这个问题,希望得到一些帮助!感谢阅读!

首先,您需要传入要处理的对象,因此您的函数签名为:

function myfunction (obj, mod, name, replace) {
  // Code
}

思路很简单:
您遍历数组中的对象,如果模块名称与您想要的相同,则检查 customUrl 的键以找到指定的键并将其替换为您的新值。

完整函数如下:

function myfunction (obj, mod, name, replace) {
  _.each(obj, function(item) {
    if (item.module === mod) {
      _.each(item.customUrl, function(innerItem) {
        if (_.has(innerItem, name)) {
          innerItem[name] = replace;
        }
      });
    }
  });
}

here is a jsbin也有一个简单的测试。单击右上角的 在 JS Bin 中编辑,您应该会在 控制台 选项卡中看到结果。

真的有必要用下划线吗?我宁愿用纯粹的 Javascript 来做。这里是一个更改已发送集合的工作示例。

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

var myFunction = function(collection, mod, name, replace){
    var module, customUrl;

    module = collection.filter(function (elem) {
        return elem.module === mod;
    })[0];

    if (!module) {
        return collection;
    }

    customUrl = module.customUrl.filter(function (url) {
        return (typeof(url[name]) !== 'undefined')
    })[0];

    if (!customUrl) {
        return collection;
    }

    customUrl[name] = replace;

    return collection;
}

var returning = myFunction(testStates, 'module2', 'mod4', 'I changed this');

console.log(JSON.stringify(returning));
console.log(JSON.stringify(testStates));