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

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);

Leave a Comment