如何设置javascript对象数组中所有对象的特定属性值(lodash)

我有以下对象数组:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "abc",
    status: "active"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: "inactive"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def"
  },
  ...
]

如何将每个对象的“status”属性设置为“active”.因此得到的数组将是:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "abc",
    status: "active"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: "active"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: "active"
  },
  ...
]

此外,如果不存在,这应该创建属性“活动”.

我可以使用for循环来做到这一点.但我非常确定lodash可以在一行中做到这一点:

arr = _.set_property(arr, "status", "active");
最佳答案
实际上,你不需要Lodash,但这个问题被标记为Lodash,并且使用Lodash提供了一些有用的防御措施,可以降低错误风险.该解决方案使用_.forEach_.set

 // _.forEach won't throw errors if arr is not an array...
 _.forEach(arr, function (obj) {
    // _.set won't throw errors if obj is not an object. With more complex objects, if a portion of the path doesn't exist, _.set creates it
     _.set(obj, 'status', 'active');
 });

如果你想把它抽象化,你可以构建一个Lodash mixin:

_.mixin({
    setProperty: function(arr, key, val) {
        _.forEach(arr, function (obj) {
            _.set(obj, path, val);
        });
    }
});

然后,您可以完全按照您的描述使用它:

_.setProperty( arr, 'status', 'active' );

转载注明原文:如何设置javascript对象数组中所有对象的特定属性值(lodash) - 代码日志