javascript - 是否有 lodash 函数或 'lodash way' 来执行条件 _.map?

标签 javascript dictionary functional-programming lodash

基本上,我有一个对象数组,我只想更新数组中满足条件的对象。我想知道是否有解决该问题的有效方法。现在我正在使用 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"}];

最佳答案

这里不需要使用map方法。

您可以通过向其传递一个回调函数来使用一个简单的forEach函数。

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

关于javascript - 是否有 lodash 函数或 'lodash way' 来执行条件 _.map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231924/

相关文章:

dictionary - 编码一个 [String : Encodable] dictionary into JSON using JSONEncoder in Swift 4

c# - 什么时候使用闭包?

javascript - 使用javascript和css设置DIV的滚动高度

ms-access - 如何在 VBA 中创建字典集合?

javascript - 将多个 Nodejs 导出返回值分配给变量时出现问题

c# - MVC ViewModel 包含一个字典,用于将空值返回给 Controller 的字段

list - 向左和向右折叠无限列表

functional-programming - 如何在 Dr.Racket 中重新分配值

backbone.js - 一个实例中的 Backbone 模型更改数据会影响另一个实例

javascript - pointerdown vs onclick : what is the difference?