首页 > 代码库 > lodash常用
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"}
转载至: https://colintoh.com/blog/lodash-10-javascript-utility-functions-stop-rewriting#2)_loop_through_a_collection_and_return_a_deeply-nested_property_from_each_item
lodash常用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。