Lodash: How to add new field to all values in collection

sowdri picture sowdri · Nov 14, 2013 · Viewed 47.9k times · Source

Example:

var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}]  
var newArr = _.enhance(arr, { married : false });

console.log(newArr); // [{name: 'a', age: 23, married : false}, {name: 'b', age: 24, married : false}]

I'm looking for something to do this. Note, enhance is not present in lodash. Is it possible to do this with lodash?
If not -- possible addition?

Thanks,

Answer

Mathletics picture Mathletics · Nov 14, 2013

You probably want to extend each of your objects.

mu is too short sort of killed my wordplay while making an excellent point. Updated to create an entirely new array.

var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}];

var newArr = _.map(arr, function(element) { 
     return _.extend({}, element, {married: false});
});

If you want to add it to the library,

_.enhance = function(list, source) {
    return _.map(list, function(element) { return _.extend({}, element, source); });   
}