24

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");
sithumc
  • 3,254
  • 8
  • 27
  • 46
  • Possible duplicate of [How to replace an object in object array in javascript (lodash)](http://stackoverflow.com/questions/42265987/how-to-replace-an-object-in-object-array-in-javascript-lodash) – guest271314 Feb 16 '17 at 23:21
  • Hi try this link its trying to do the same but by index. http://stackoverflow.com/questions/27641731/is-there-a-function-in-lodash-to-replace-matched-item – Arif Imtiaz Feb 16 '17 at 23:24
  • `arr.forEach(it=>it.status='active');` use the force Luke. Take time to look at global standard JavaScript objects and methods for `Array` and `Object`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects instead of using duplication of outdated libraries and thereby maintain practical knowledge – jimmont Feb 08 '20 at 19:28

3 Answers3

26

You don't need lodash for this.


The first object is missing your status property and it will be added.


SHOWING THREE WAYS HOW YOU CAN DO IT


IMMUTABLE VERSION (We create a new array using map)

const arrImmutableVersion = arr.map(e => ({...e, status: "active"}));

MUTABLE VERSIONS (We change the original array)

arr.forEach((el)=>{el.status = "active";}) 

or

arr.forEach(function(el){el.status = "active";}) 

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

// SHOWING THREE WAYS HOW YOU CAN DO IT

// MUTABLE VERSIONS - We change the original array
arr.forEach((el)=>{el.status = "active";}) // ES6
// or
arr.forEach(function(el){el.status = "active";}) 
//or
// IMMUTABLE VERSION - We create a new array using `map`
const arrImmutableVersion = arr.map(e => ({...e, status: "active"})); // ES6
//--------------------------------------------------------------


// RESULTS:
console.log("logging results of object 'arr'");
console.log(arr);
console.log("---------------------------------------------------------");
console.log("logging results of object 'arrImmutableVersion'");
console.log(arrImmutableVersion);
Legends
  • 21,202
  • 16
  • 97
  • 123
12

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' );
random_user_name
  • 25,694
  • 7
  • 76
  • 115
3

A way simpler and and cleaner way !

If you want to use func programming in a proper manner

  myArray = myArray.map(arrayElem => {
    arrayElem.property = newValue
    return arrayElem
  })
Shady Smaoui
  • 867
  • 9
  • 11