lodash常用
Posted 戴杭林
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lodash常用相关的知识,希望对你有一定的参考价值。
1) Loop for N times
// 1. Basic for loop.
for(var i = 0; i < 5; i++) {
// ....
}
// 2. Using Array‘s join and split methods
Array.apply(null, Array(5)).forEach(function(){
// ...
});
// Lodash
_.times(5, function(){
// ...
});
2) Loop through a collection and return a deeply-nested property from each item
// Fetch the name of the first pet from each owner
var ownerArr = [{
"owner": "Colin",
"pets": [{"name":"dog1"}, {"name": "dog2"}]
}, {
"owner": "John",
"pets": [{"name":"dog3"}, {"name": "dog4"}]
}];
// Array‘s map method.
ownerArr.map(function(owner){
return owner.pets[0].name;
});
// Lodash
_.map(ownerArr, ‘pets[0].name‘);
3) Create an array of N size and populate them with unique values of the same prefix
// Create an array of length 6 and populate them with unique values. The value must be prefix with "ball_".
// eg. [ball_0, ball_1, ball_2, ball_3, ball_4, ball_5]
// Array‘s map method.
Array.apply(null, Array(6)).map(function(item, index){
return "ball_" + index;
});
// Lodash
_.times(6, _.uniqueId.bind(null, ‘ball_‘));
4) Deep-cloning Javascript object
var objA = {
"name": "colin"
}
// Normal method? Too long. See Stackoverflow for solution: http://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript
// Lodash
var objB = _.cloneDeep(objA);
objB === objA // false
5) Get Random Number between a range
// Get a random number between 15 and 20.
// Naive utility method
function getRandomNumber(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
getRandomNumber(15, 20);
// Lodash
_.random(15, 20);
6) Extending object
// Adding extend function to Object.prototype
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
var objA = {"name": "colin", "car": "suzuki"};
var objB = {"name": "james", "age": 17};
objA.extend(objB);
objA; // {"name": "james", "age": 17, "car": "suzuki"};
// Lodash
_.assign(objA, objB);
Extending multiple objects
var objA = {"name": "colin", "car": "suzuki"};
var objB = {"name": "james", "age": 17};
var objC = {"pet": "dog"};
// Lodash
_.assign(objA, objB, objC)
// {"name": "james", "car": "suzuki", "age": 17, "pet": "dog"}
7) Removing properties from object
// Naive method: Remove an array of keys from object
Object.prototype.remove = function(arr) {
var that = this;
arr.forEach(function(key){
delete(that[key]);
});
};
var objA = {"name": "colin", "car": "suzuki", "age": 17};
objA.remove([‘car‘, ‘age‘]);
objA; // {"name": "colin"}
// Lodash objA = _.omit(objA, [‘car‘, ‘age‘]); // {"name": "colin"}
More use-cases
var objA = {"name": "colin", "car": "suzuki", "age": 17};
// Lodash
objA = _.omit(objA, ‘car‘); // {"name": "colin", "age": 17};
objA = _.omit(objA, _.isNumber); // {"name": "colin"};
8) Select properties from another object to form new object
// Naive method: Returning a new object with selected properties
Object.prototype.pick = function(arr) {
var _this = this;
var obj = {};
arr.forEach(function(key){
obj[key] = _this[key];
});
return obj;
};
var objA = {"name": "colin", "car": "suzuki", "age": 17};
var objB = objA.pick([‘car‘, ‘age‘]);
// {"car": "suzuki", "age": 17}
// Lodash
var objB = _.pick(objA, [‘car‘, ‘age‘]);
// {"car": "suzuki", "age": 17}
9) Selecting a random item from a list
var luckyDraw = ["Colin", "John", "James", "Lily", "Mary"];
function pickRandomPerson(luckyDraw){
var index = Math.floor(Math.random() * (luckyDraw.length));
return luckyDraw[index];
}
pickRandomPerson(luckyDraw); // John
// Lodash
_.sample(luckyDraw); // Colin
10) Error handling for JSON.parse
// Using try-catch to handle the JSON.parse error
function parse(str){
try {
return JSON.parse(str);
}
catch(e) {
return false;
}
}
// With Lodash
function parseLodash(str){
return _.attempt(JSON.parse.bind(null, str));
}
parse(‘a‘); // false
parseLodash(‘a‘); // Return an error object
parse(‘{"name": "colin"}‘); // Return {"name": "colin"}
parseLodash(‘{"name": "colin"}‘); // Return {"name": "colin"}
以上是关于lodash常用的主要内容,如果未能解决你的问题,请参考以下文章