Collect.js flatMap() 方法
Collect.js是一个用于处理数组和对象的包装库,它无依赖且易于使用。 flatMap()方法用于迭代所有集合元素并将每个集合元素传递给给定的回调。
句法:
collect(array).flatMap(callback)
参数: collect()方法采用一个参数,该参数转换为集合,然后对其应用flatMap()方法。 flatMap()方法拥有一个单参数回调函数。
示例 1:下面的示例说明了collect.js中的flatMap()方法
html
const collect = require('collect.js');
let obj = [
{
name: 'Rahul',
score: 98,
},
{
name: 'Aditya',
score: 96,
},
{
name: 'Abhishek',
score: 80
}
];
const collection = collect(obj);
const map_Val = collection.flatMap(
element => element.name.toUpperCase());
console.log(map_Val.all());
html
const collect = require('collect.js');
let obj = [
{
name: 'Rahul',
score: 98,
},
{
name: 'Aditya',
score: 96,
},
{
name: 'Abhishek',
score: 80
},
{
name: 'Rahul',
score: 77,
},
];
const collection = collect(obj);
const map_Val = collection.flatMap(
element => element.score > 80);
console.log(map_Val.all());
输出:
[ 'RAHUL', 'ADITYA', 'ABHISHEK' ]
示例 2:
html
const collect = require('collect.js');
let obj = [
{
name: 'Rahul',
score: 98,
},
{
name: 'Aditya',
score: 96,
},
{
name: 'Abhishek',
score: 80
},
{
name: 'Rahul',
score: 77,
},
];
const collection = collect(obj);
const map_Val = collection.flatMap(
element => element.score > 80);
console.log(map_Val.all());
输出:
[ true, true, false, false ]