ABOUT ME

-

Total
-
  • JS Lodash 튜토리얼
    컴퓨터/HTML & JS & TS 2020. 8. 15. 10:25
    728x90
    반응형

    Lodash

     

    Lodash

    _.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn

    lodash.com

    0. 소개

    JQuery처럼 자바스크립트 유틸리티 라이브러리 중 하나인데, _(underscore) 라이브러리 파생

    React 프로젝트에서도 많이 쓰이며, 요즘 인기가 제일 많다.

    1. 설치법

    HTML 스크립트 부분에 아래를 추가하고, npm으로 설치한다.

    <script src="https://raw.githubusercontent.com/lodash/lodash/4.17.15-npm/lodash.min.js"></script>
    npm i --save lodash

     

     

    혹은, gatsby나 react-create-app으로 베이스를 만들어서, yarn으로 설치

    yarn add lodash

     

    2. 사용법

    Interactive 모드에서 테스트하고 싶으면, n_ 설치 후, 터미널에서 n_ 을 입력하면 된다.

    npm install -g n_

    혹은 JS에 import

    import _ from "lodash"

     

    3. 주요 함수 목록

     

    _.head( array )

    기능 : 배열에서 첫 번째 요소를 가져온다.

    return : array[0]

    _.head([1, 2, 3]);
    // => 1
     
    _.head([]);
    // => undefined

     

    _.last( array )

    기능 : 배열에서 마지막 요소를 가져온다.

    return : array[-1]

    _.last([1, 2, 3]);
    // => 3

     

    _.assign( object, [source] )

    기능 : Assigns own enumerable string keyed properties of source objects to the destination object.

    return : Object

    링크 : https://lodash.com/docs/4.17.15#assign

    function Foo() {
      this.a = 1;
    }
     
    function Bar() {
      this.c = 3;
    }
     
    Foo.prototype.b = 2;
    Bar.prototype.d = 4;
     
    _.assign({ 'a': 0 }, new Foo, new Bar);
    // => { 'a': 1, 'c': 3 }

     

    _.get( object, path, [defaultValue] )

    기능 : path 의 object에서 값을 가져온다.

    return : Object

    링크 : https://lodash.com/docs/4.17.15#get

    var object = { 'a': [{ 'b': { 'c': 3 } }] };
     
    _.get(object, 'a[0].b.c');
    // => 3
     
    _.get(object, ['a', '0', 'b', 'c']);
    // => 3
     
    _.get(object, 'a.b.c', 'default');
    // => 'default'
    // React 에서 array 배열 list 만들기
    
    let array = [1, 2, 3]
    
    <ul>
      {_.map(array, value => (
        <li key={value}>{value}</li>
      ))}
    </ul>

    Form 만들기

     

    _.map( collection, [iteratee=_.identity] )

    기능 : iteratee를 통해 collection 각 요소들을 통해 array를 만든다.

    return : Array

    링크 : https://lodash.com/docs/4.17.15#map

    function square(n) {
      return n * n;
    }
     
    _.map([4, 8], square);
    // => [16, 64]
     
    _.map({ 'a': 4, 'b': 8 }, square);
    // => [16, 64] (순서는 보장되지 않음)
     
    var users = [
      { 'user': 'barney' },
      { 'user': 'fred' }
    ];
     
    // value iterate
    _.map(users, 'user');
    // => ['barney', 'fred']

     

    _.sample( collection )

    기능 : collection에서 random으로 값을 리턴한다.

    return : random element of collection

    링크 : https://lodash.com/docs/4.17.15#sample

    _.sample([1, 2, 3, 4]);
    // => 2

     

    _.partition( object, path, [defaultValue] )

    기능 : path 의 object에서 값을 가져온다.

    return : Object

    링크 : https://lodash.com/docs/4.17.15#partition

    var cards = [
        {suit: 'clubs', val: '1', desc: 'ace'},
        {suit: 'spades', val: '11', desc: 'jack'},
        {suit: 'hearts', val: '5', desc: '5'},
        {suit: 'hearts', val: '6', desc: '6'},
        {suit: 'diamonds', val: '7', desc: '7'},
        {suit: 'clubs', val: '13', desc: 'king'},
        {suit: 'hearts', val: '12', desc: 'queen'},
     
    ];
    
    let i = 0;
    
    _.each(_.partition(cards, function(card){
     
       return card.val >= 11;  // val이 11이상과 미만 파티션 나눔
     
    }), function(part){
        console.log('** part: ' + i + ' **');
        _.each(part, function(card){
            console.log(card.desc);
        });
        i += 1;
     
    });
    /* 출력
    ** part: 0 **
    jack
    king
    queen
    ** part: 1 **
    ace
    5
    6
    7
    */

     

    _.forEach( collection, [iteratee=_.identity] )

    기능 : collection을 각 element마다 itertaee를 실행하여 출력한다.

    return : Collection

    링크 : https://lodash.com/docs/4.17.15#forEach

    _.forEach([1, 2], function(value) {
      console.log(value);
    });
    // => Logs `1` 다음 `2`.
     
    _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
      console.log(key);
    });
    // => Logs 'a' 다음 'b' (순서는 보장되지 않음).

     

    _.forIn( object, [iteratee=_.identity] )

    기능 : object의 요소마다 iteration function 실행

    return : Object

    링크 : https://lodash.com/docs/4.17.15#forIn

    function Foo() {
      this.a = 1;
      this.b = 2;
    }
     
    Foo.prototype.c = 3;
     
    _.forIn(new Foo, function(value, key) {
      console.log(key);
    });
    // => Logs 'a', 'b', 그다음 'c' (순서는 보장되지 않음).

     

    아래는 Gatsby로 간단한 lodash 사용

    import React from "react"
    import { Link } from "gatsby"
    
    import Layout from "../components/layout"
    import SEO from "../components/seo"
    
    import _ from "lodash"
    
    const ver = _.VERSION
    
    let words = ["sky", "wood", "forest", "falcon", "pear", "ocean", "universe"]
    
    let nums = [1, 2, 3, 4, 5, 6, 7, 8]
    
    const IndexPage = () => (
      <Layout>
        <SEO title="Home " />
        <h1>Node Version {ver}&lt;/h1>
        <p>
          first and last : {_.first(words)} and {_.last(words)}
        </p>
        <p>
          Array usage : {_.nth(nums, 3)} + {_.random(10)} + {_.sample(words)}
        </p>
        <p>
          {_.nth(nums, 3)} + {_.random(10)} + {_.sample(words)}
        </p>
        {_.times(4, () => {
          console.log("tims function")
        })}
        <Link to="/page-2/">Go to page 2</Link> <br />
        <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
      </Layout>
    )
    
    export default IndexPage
    
    728x90

    댓글