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常用的更多相关文章

  1. lodash常用函数 - Array、Collection

    lodash常用函数 - Array.Collection lodash版本 v3.10.1 1.Array.Collection pull 移除数组中满足条件的元素 var array = [1, ...

  2. Lodash 常用API中文参考

    lodash和underscore都是现在非常流行的两个javascript库,提供了一套函数式编程的实用功能. 而lodash本身最初也是underscore的一个fork,因为和其他(Unders ...

  3. 函数式编程 lodash 常用api

    1.forEach _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { console.log(key); }); _.forEach([3,4] ...

  4. [转] Lodash常用API笔记

    原生用法 直接使用的API _.reject 根据条件去除某个元素. var foo = [ {id: 0, name: "aaa", age: 33}, {id: 1, name ...

  5. lodash

    lodash常用函数一 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  6. lodash 工具库

    lodash是一套工具库,内部封装了很多字符串.数组.对象等常见数据类型的处理函数. 1.lodash的引用 import _ from 'lodash' 用一个数组遍历来说明为什么要使用lodash ...

  7. Lodash.js常用拷贝

    lodash.js 降低 array.number.objects.string 等等的使用难度从而让 JavaScript 变得更简单.非常适用于:遍历 array.object 和 string: ...

  8. lodash 中常用的方法

    odash是js集Array/Object/String/Function的Util于一身. lodash打包了Array/Object/String/Function里一些Api,好处是连ES6的也 ...

  9. Node填坑教程——常用库

    作为函数式编程来说,流程控制和函数库是必不可少的(应该吧). 下面我们介绍两个常用的库. lodash:完整的api请参阅,https://lodash.com/docs.这里我们只演示几个简单的例子 ...

随机推荐

  1. PyCharm2019 激活方式

    1.修改hosts激活:需要修改hosts,稳定无影响,持续更新,推荐~ 一.修改hosts激活 1.修改hosts文件 将0.0.0.0 account.jetbrains.com和0.0.0.0 ...

  2. 封装,封装的原理,Property ,setter ,deleter,多态,内置函数 ,__str__ , __del__,反射,动态导入模块

    1,封装 ## 什么是封装 what 对外隐藏内部的属性,以及实现细节,并给外部提供使用的接口 学习封装的目的:就是为了能够限制外界对内部数据的方法 注意 :封装有隐藏的意思,但不是单纯的隐藏 pyt ...

  3. shell-code-拷贝文件

    #!/bin/bash while read F do cp ${F}"_pe_1.fastq.gz" /public/home/chenjy/usr/ZD/data/cleand ...

  4. build_mem_type_table

    该函数设置mem_types结构体数组,结构体定义如下: struct mem_type { unsigned int prot_pte;     //二级页表属性 unsigned int prot ...

  5. Cleaning Shifts POJ - 2376 (贪心题)

    Cleaning Shifts Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 31194   Accepted: 7677 ...

  6. javaweb通过接口来实现多个文件压缩和下载(包括单文件下载,多文件批量下载)

    原博客地址:https://blog.csdn.net/weixin_37766296/article/details/80044000 将多个文件压缩并下载下来:(绿色为修改原博客的位置) 注意:需 ...

  7. CodeForces 570D DFS序 树状数组 Tree Requests

    参考九野巨巨的博客. 查询一个子树内的信息,可以通过DFS序转成线形的,从而用数据结构来维护. #include <iostream> #include <cstdio> #i ...

  8. Java中String类通过new创建和直接赋值字符串的区别

    方式一:String a = “aaa” ; 方式二:String b = new String(“aaa”); 两种方式都能创建字符串对象,但方式一要比方式二更优. 因为字符串是保存在常量池中的,而 ...

  9. tomcat6-输入输出buffer设计

    之前写的一个ppt 搬到博客来

  10. webdriver高级应用- 在HTML5的画布元素上进行绘画操作

    #encoding=utf-8 import unittest from selenium import webdriver import time class TestDemo(unittest.T ...