I am trying to use underscore.js _.map
function on an array of objects, to get an array with a property of each object. That's the usual scenario, so :
var finalArray = _.map(myArray, function(obj) { return obj.myProperty; });
But in some cases I need that nothing be added in the array. It could be something like :
var finalArray = _.map(myArray, function(obj) { if (!obj.ignore) { return obj.myProperty; } });
The result of this is that an undefined
value is pushed into the array, which is not the same as not pushing anything at all.
Is there a way for the map function not to push a value, or do I need to post-process my finalArray
to remove the unwanted undefined
's?
js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. map() method creates an array of values by running each element in collection through the iteratee.
Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
you should use _.filter() before _.map()
var filteredArray = _.filter(myArray,function(obj) { return !obj.ignore; }); var finalArray = _.map(filteredArray, function(obj) { return obj.myProperty; });
You could use reduce:
myArray.reduce(function (acc, obj) { if (!obj.ignore) { acc.push(obj.myProperty); } return acc; }, []);
or with lodash:
_.reduce(myArray, function (acc, obj) { if (!obj.ignore) { acc.push(obj.myProperty); } return acc; }, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With