代码之家  ›  专栏  ›  技术社区  ›  Shobi

如何正确链接lodash函数调用

  •  0
  • Shobi  · 技术社区  · 6 年前

    我需要对一组对象进行排序,然后从中提取第一项。如何在洛达斯实现这一点?

    _.sortBy(window.locations, [{ 'is_primary': 'desc' }])
    

    _.first() 功能?可能是锁链?

    2 回复  |  直到 6 年前
        1
  •  3
  •   SzybkiSasza    6 年前

    你可以用 _.chain 然后展开值:

    https://lodash.com/docs/4.17.10#chain

    _.first 因为洛达斯被保护 undefined ,空数组, null 以此类推(最糟糕的情况是返回空数组):

    _.first(_.sortBy(window.locations, [{ 'is_primary': 'desc' }]));
    

    _.链条 在浏览器环境中-它可能会导致包显著增长(因为它可能包含很多 lodash 如果您对此感到担忧,请阅读本文:

    https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba

    热释光;博士 如果您正在执行简单的操作,并且关心输出JS包的大小,请坚持只使用包装 _第一个

        2
  •  1
  •   Akrion    6 年前

    首先让我们注意到 _.first is a alias of _.head

    还有一点需要注意 _.sortBy _.orderBy 这总是会出现,也应该注意:

    _.sortBy short 表示法或通过函数但是 只按升序 !

    _.orderBy 执行相同的操作,但允许您指定多个字段 以及它们的排序顺序(asc/desc) .

    考虑以下示例:

    var users = [
      { 'user': 'fred',   'age': 1, 'drinks': 1 },
      { 'user': 'barney', 'age': 4, 'drinks': 3 },
      { 'user': 'brat',   'age': 4, 'drinks': 6 },
      { 'user': 'josh',   'age': 2, 'drinks': 2 },
      { 'user': 'jim',    'age': 2, 'drinks': 10 },
      { 'user': 'barney', 'age': 3, 'drinks': 5}
    ];
    
    const sortBy = _.sortBy(users, ['age','drinks'])
    const orderBy = _.orderBy(users, ['age', 'drinks'], ['asc', 'desc'])
    
    console.log('sortBy', sortBy)
    console.log('orderBy', orderBy)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    orderBy 因为它的方便。

    回到你的问题上来:

    您可以使用以下任何一种:

    // ONLY ASC
    _.head(_.sortBy(window.locations, ['is_primary']));
    _.first(_.sortBy(window.locations, ['is_primary']));
    
    // ASC & DESC
    _.head(_.orderBy(window.locations, ['is_primary'], ['desc']));
    _.first(_.orderBy(window.locations, ['is_primary'], ['desc']));
    

    最后一个 chaining 总体来说主要是为了方便和可读性。如果你有两个以上的操作,阅读起来会很困难,所以规则通常是如果超过2,那么链,但是如果等于或小于这个,就不需要了。

    在大多数使用链接的示例中,它应用于2个以上的操作。