Search code examples
javascriptlodash

How to set specific property value of all objects in a javascript object array (lodash)


I have following object array:

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

How to set "status" property of each object to "active". So the resulting array will be:

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"
  },
  ...
]

Additionally this should create the property "active" if doesn't exists.

I can do this using for loops. But I'm pretty much sure lodash can do this in one line like:

arr = _.set_property(arr, "status", "active");

Solution

  • Indeed, you don't need Lodash, but the question is tagged Lodash, and using Lodash offers some useful defenses that reduces the risk of errors. This solution utilizes _.forEach and _.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');
     });
    

    If you wanted to make it abstract, you could build a Lodash mixin:

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

    Then, you could use it exactly as you described:

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