Search code examples
angulartypescriptlodash

Lodash set not applying update to array


I am trying to update the 'mobileNumber' field of all elements in an array. I have tried the following suggestions here on StackOverflow, but none seem to update the field in the array.

_.each(results, function(item) {
  _.set(item, 'mobileNumber', 2);
});

const formattedResults = _.each(results, function(item) {
  _.set(item, 'mobileNumber', 2);
});

What am I doing wrong?

EDIT : It turns out in Typescript that even assigning my original array to a new array using let, somehow kept the new array readonly too.

I ended up using lodash _clone, before setting the value, and then the update worked...

let formattedResults = _.map(results, _.clone);

Solution

  • What you have done is actually correct check here https://jsbin.com/fiyinahovi/edit?js,console

    let results = [{mobileNumber: 1}, {mobileNumber: 3}, {mobileNumber: 7}]
    _.each(results, function(item) {
      _.set(item, 'mobileNumber', 2);
    });
    
    console.log(results);