Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 256
sowdri Avatar asked Nov 14 '13 01:11

sowdri


People also ask

What is _ get?

Overview. The _. get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

What is Lodash flatten?

The Lodash. flatten() method is used to flatten the array to one level deep. Syntax: flatten( array ) Parameter: This method accepts single parameter array that holds simple array or array of arrays. Return Value: The return type of this function is array.

What is Lodash isEqual?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent.


1 Answers

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); });    } 
like image 112
Mathletics Avatar answered Sep 21 '22 06:09

Mathletics