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


Collect.js mapInto()用法及代碼示例


mapInto()方法用於遍曆collection元素,並使用每個元素作為構造函數實例化給定的類。

用法:

collect(array).mapInto()

參數:collect()方法采用一個參數,該參數將轉換為集合,然後在其上應用mapInto()方法。

返回值:此方法返回映射的集合元素。

下麵的示例說明了collect.js中的mapInto()方法:



範例1:

Javascript

const collect = require('collect.js'); 
  
const data = function (name) { 
    this.name = name; 
}; 
  
const arr = ['GFG', 'Geeks', 'GeeksforGeeks']; 
  
const collection = collect(arr); 
  
const elements = collection.mapInto(data); 
  
console.log(elements.all());

輸出:

[
  data { name:'GFG' },
  data { name:'Geeks' },
  data { name:'GeeksforGeeks' }
]

範例2:

Javascript

const collect = require('collect.js'); 
  
const data = function (name, dob) { 
    this.name = name; 
    this.dob = dob; 
}; 
  
let obj = [ 
    { 
        name:'Rahul', 
        dob:'25-10-96', 
        section:'A', 
        score:98, 
    }, 
    { 
        name:'Aditya', 
        dob:'25-10-96', 
        section:'B', 
        score:96, 
    }, 
    { 
        name:'Abhishek', 
        dob:'16-08-94', 
        section:'A', 
        score:80 
    }, 
    { 
        name:'Rahul', 
        dob:'19-08-96', 
        section:'B', 
        score:77, 
    }, 
]; 
  
const collection = collect(obj); 
  
const objects = collection.mapInto(data); 
  
console.log(objects.all());

輸出:

[
  data {
    name:{ 
      name:'Rahul', 
      dob:'25-10-96', 
      section:'A', 
      score:98 
    },
    dob:0
  },
  data {
    name:{ 
      name:'Aditya', 
      dob:'25-10-96', 
      section:'B', 
      score:96 },
    dob:1
  },
  data {
    name:{ 
      name:'Abhishek', 
      dob:'16-08-94', 
      section:'A', 
      score:80 
    },
    dob:2
  },
  data {
    name:{ 
      name:'Rahul', 
      dob:'19-08-96', 
      section:'B', 
      score:77 
    },
    dob:3
  }
]

相關用法


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