【问题标题】:Is there a lodash function or a 'lodash way' to do a conditional _.map?是否有 lodash 函数或“lodash 方式”来执行条件 _.map?
【发布时间】:2018-04-24 05:20:20
【问题描述】:

所以基本上,我有一个对象数组,我想只更新数组中满足条件的对象。我想知道是否有解决这个问题的好方法。现在我正在使用 lodash。这是和示例:

var things = [
    {id: 1, type: "a", value: "100"}, 
    {id: 2, type: "b", value: "300"}, 
    {id: 3, type: "a", value: "100"}
];
var results = _.map(things, function (thing) { 
    if(thing.type === "a") {
        thing.value = "500";
    } 
    return thing;
});
// => results should be [{id: 1, type: "a", value: "500"}, {id: 2, type: "b", value: "300"}, {id: 3, type: "a", value: "500"}];

【问题讨论】:

    标签: javascript dictionary functional-programming lodash


    【解决方案1】:

    这里不需要使用map方法。

    您可以通过将 回调 函数传递给它来使用简单的 forEach 函数。

    var results = _.forEach(things, function (thing) { 
      if(thing.type === "a") {
        thing.value = "500";
      } 
    });
    

    【讨论】:

      【解决方案2】:

      您可以只使用Object.assign 内的条件映射新对象,而不改变原始对象。

      var things = [{ id: 1, type: "a", value: "100" }, { id: 2, type: "b", value: "300" }, { id: 3, type: "a", value: "100" }],
          results = things.map(o => Object.assign({}, o, o.type === "a" && { value: 500 }));
      
      console.log(results);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案3】:

        您可以将Array#map(或Lodash 的等效项)与三元组一起使用,如果类型为a,则使用Object#assign 创建一个新的更新对象:

        var things = [
            {id: 1, type: "a", value: "100"}, 
            {id: 2, type: "b", value: "300"}, 
            {id: 3, type: "a", value: "100"}
        ];
        var result = things.map(function (thing) { 
            return thing.type === 'a' ? Object.assign({}, thing, { value: 500 }) : thing;
        });
        
        console.log(result);

        【讨论】:

          【解决方案4】:

          这可能有点早,但使用目前处于第 3 阶段的proposal for object rest spread,您可以像这样解决它:

          const things = [
              {id: 1, type: "a", value: "100"}, 
              {id: 2, type: "b", value: "300"}, 
              {id: 3, type: "a", value: "100"},
          ];
          const result = things.map(e => e.type === 'a' ? {...e, value: 500 } : e);
          console.log(result);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-06-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-07-09
            • 2015-10-13
            • 1970-01-01
            相关资源
            最近更新 更多