Getting to know lodash
So here in the bunker we have some real old school javascript code. Lodash is nowhere is sight :-). I spend a lot of time working with an api that returns json (nice). However it’s not all good. Having to transform the data is the most common task, not only that but some data mapping and mutations. Now as if that were not enough, we have to do some stuff with dates, that’s right dates. We are using AngularJS right now, yes it’s 2019, I could cry. :-) :cry:
For a moment let’s pretend we have some data from our api. A common issue for us is. Did we get the data we expected? Is this and array?
We can replace this type of code by using lodash “_.forEach”. Unless you need the index for some reason then just stop using the old school for loops.
Replace array checks with _.forEach
if (arrayData && arrayData.length > 0) {
for(let i = 0; i < arrayData.length; i++) {
//do the magic
}
}
//Do this instead, let lodash do the check for you
_.forEach(arrayData, function(item) {
//do the magic
});
Pick the first item with a value “_.first”
Say you have a list of possible values, and you need to pick the one with a value. How about picking a date, but sometimes the dates are null or undefined. In the example the first date is undefined, but that my not always be the case, Sometimes there none will have a date.
Replace nested if statments with find first
var data = {
startDate : undefined,
anotherStartDate = "10-10-2010",
claimDate = "10-10-2015"
}
//Not recomended
if (data.startDate) {
return data.startDate;
} else if (anotherStartDate) {
return data.anotherStartDate;
} else if (claimDate) {
data.claimDate;
}
var someDates = [data.startDate, data.anotherStartDate, data.claimDate];
_.first(someDates, function(item) {
return item !== undefined;
});
Map data “_.map”
Now we all know that data mutations are a bad thing right?
What’s a mutation? An immutable value is one that, once created, can never be changed. In JavaScript, primitive values such as numbers, strings and booleans are always immutable. However, data structures like objects and arrays are not.
Mapping objects really is the way to go and guess what? lodash has you covered there as well.
var result = _.map(data, function(item) {
return {
"myStartDate" : format(data.myStartDate, "dd/mmmm/yyyy"),
"summaryLine" : data.startLine + " " + data.endLine;
}
});
Range
I do like this, want to print out 0 to 10
_.each(_.range(10), (value) => console.log(value));