當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.flatMapDeep()用法及代碼示例

Lodash是一個JavaScript庫,可在underscore.js頂部使用。 Lodash幫助處理數組,集合,字符串,對象,數字等。

_.flatMapDeep()方法通過通過iteratee函數運行給定集合中的每個元素來創建平坦的值數組,並遞歸地平坦化映射的結果。它類似於_.flatMap()方法。

用法:

_.flatMapDeep( collection, iteratee )

參數:該方法接受上述和以下所述的兩個參數:

  • collection:它是要迭代的集合。
  • iteratee:每次迭代調用的函數。

返回值:此方法返回新的展平的數組。



範例1:

// Requiring the lodash library  
const _ = require("lodash"); 
      
// Original array  
var users = (['aaa', 'bbb', 'ccc',  
              'ddd', 'eee', 'fff']); 
  
// Using the _.flatMapDeep() method 
let flat_map = 
  _.flatMapDeep(users, 
    function duplicate(n) { 
      return [[[n, n]]]; 
  } 
) 
  
// Printing the output  
console.log(flat_map);

輸出:

[
  'aaa', 'aaa', 'bbb', 'bbb',
  'ccc', 'ccc', 'ddd', 'ddd',
  'eee', 'eee'
]

範例2:

// Requiring the lodash library  
const _ = require("lodash");  
      
// Original array  
var user1 = ([1, 2, 3, 4, 5, 6, 7]); 
var user2 = (['a', 'b', 'c', 'd', 'e']); 
  
// Using the _.flatMapDeep() method 
let flat_map1 = 
  _.flatMapDeep(user1, 
    function makePattern(n) { 
      return [[[n, n + "->"]]]; 
  } 
) 
   
let flat_map2 = 
  _.flatMapDeep(user2, 
    function makePattern(n) { 
      return [[["<-" + n, n]]]; 
  } 
) 
  
// Printing the output  
console.log(flat_map1); 
console.log(flat_map2);

輸出:

[
  1, 1->, 2, 2->, 3, 3->,
  4, 4->, 5, 5->, 6, 6->,
  7, 7->
]
[
  '<-a', 'a', <-'b', 'b',
  '<-c', 'c', '<-d', 'd',
  '<-e', 'e'
]




相關用法


注:本文由純淨天空篩選整理自shivanisinghss2110大神的英文原創作品 Lodash _.flatMapDeep() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。