支持 Laravel.io 的持续发展 →

collect.js:JavaScript 数组的 Laravel 语法

23 Jan, 2023 7 min read

简介

Collect.js 是 Daniel Eckermann 开发的一个 JavaScript 库,它提供了在数组上方便的一层。它提供了一个几乎与 Laravel 集合 相同的 API,使得使用数组变得更加容易(至少对我来说是这样的)。

如果你像我一样,可能在处理项目时经常在 Laravel 中的 PHP 代码和前端的 JavaScript 代码之间切换。在过去的 JavaScript 数组处理中,我经常会想,“如果能有一个像 Laravel 集合中的 XYZ 方法就好了”。所以,collect.js 提供了一种非常酷的解决方案,通过提供一个与 PHP 中的 Laravel 集合一致的 API 来弥合这个差距。

在撰写本文时,collect.js 在 GitHub 上已有超过 6.1k 个 Star,每月下载量超过 110 万次!

在本文中,我们将了解 collect.js 的安装方法以及一些你可能在自己的项目中使用到的常用方法示例。

安装

安装库

要开始使用 collect.js,你可以通过在项目中运行以下命令使用 npm 安装它:

npm install collect.js --save

如果你使用 Yarn,也可以通过运行以下命令来安装它:

yarn add collect.js

另外,如果您希望通过CDN引入库,可以将以下脚本标签添加到您的HTML中

<script src="https://cdnjs.com/libraries/collect.js"></script>

引入库

安装库后,您需要将其包含在项目中以便使用。让我们看看库文档中的几个示例,了解如何引入库。

如果您想使用 require 引入

const collect = require('collect.js');

// You can then use it like so...

collect(products)
    .where('price', '>', 299);

或者,如果您想使用 import

import collect from 'collect.js';

// You can then use it like so...
  
collect(products)
    .where('price', '>', 299);

或者,如果您想使用基础类而不是使用 collect() 方法

import { Collection } from 'collect.js';

// You can then use it like so...
  
new Collection(products)
    .where('price', '>', 299);

示例

现在您已经在项目中包含了 collect.js 并准备就绪,让我们看看库文档中的一些示例,这些示例展示了您在项目中可能会使用到的不同方法

filter

filter 方法则使用提供的回调函数过滤集合,只保留通过提供的真值测试的项目。

示例

const collection = collect([1, 2, 3, 4]);

const filtered = collection.filter((value, key) => value > 2);

// 'filtered' will now only include:

// [3, 4]

reject

reject 方法是 filter 方法的逆操作。它使用提供的回调函数过滤集合,移除任何通过提供的真值测试的项目。

示例

const collection = collect([1, 2, 3, 4]);

const filtered = collection.reject(value => value > 2);

// 'filtered' will now only include:
  
// [1, 2]

map

map 方法遍历集合中的项目,并将它们传递给提供的回调函数。回调函数可以用来修改并返回项目。然后,此方法将返回一个新的集合,包含修改后的项目。

示例

const collection = collect([1, 2, 3, 4, 5]);

const multiplied = collection.map(item => item * 2);

// 'multiplied' will now only include:

// [2, 4, 6, 8, 10]

正如文档中提到的,值得注意的是,map 方法返回一个全新的集合,并不会修改现有的集合。如果您想修改现有的集合,可以使用 transform 方法代替。

firstWhere

firstWhere 方法返回集合中第一个具有给定键值对的项目。

示例

const collection = collect([
  { name: 'Regena', age: 12 },
  { name: 'Linda', age: 14 },
  { name: 'Diego', age: 23 },
  { name: 'Linda', age: 84 },
]);

const filtered = collection.firstWhere('name', 'Linda');

// 'filtered' will now only include:

// { name: 'Linda', age: 14 }

sortBy

sortBy 方法允许您使用几种不同的方法对集合进行排序。

首先,您可以使用字段名对集合进行排序,如下所示

const collection = collect([
  { name: 'Desk', price: 200 },
  { name: 'Chair', price: 100 },
  { name: 'Bookcase', price: 150 },
]);

const sorted = collection.sortBy('price');

// 'sorted' will now be:

// [
//   { name: 'Chair', price: 100 },
//   { name: 'Bookcase', price: 150 },
//   { name: 'Desk', price: 200 },
// ]

您还可以使用点表示法对包含值进行排序,如下所示

const collection = collect([
  {
    name: 'Desk',
    price: 200,
    manufacturer: {
      name: 'IKEA',
    },
  },
  {
    name: 'Chair',
    price: 100,
    manufacturer: {
      name: 'Herman Miller',
    },
  },
  {
    name: 'Bookcase',
    price: 150,
    manufacturer: {
      name: 'IKEA',
    },
  },
]);

const sorted = collection.sortBy('manufacturer.name');

// 'sorted' will now be:
  
// [
//   {
//     name: 'Chair',
//     price: 100,
//     manufacturer: {
//       name: 'Herman Miller',
//     },
//   },
//   {
//     name: 'Desk',
//     price: 200,
//     manufacturer: {
//       name: 'IKEA',
//     },
//   },
//   {
//     name: 'Bookcase',
//     price: 150,
//     manufacturer: {
//       name: 'IKEA',
//     },
//   },
// ]

或者,您还可以传递自己的自定义回调,该回调应用于对条目进行排序,如下所示

const collection = collect([
  { name: 'Desk', colors: ['Black', 'Mahogany'] },
  { name: 'Chair', colors: ['Black'] },
  { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
]);

const sorted = collection.sortBy((product, key) => product.colors.length);

// 'sorted' will now be:

// [
//   { name: 'Chair', colors: ['Black'] },
//   { name: 'Desk', colors: ['Black', 'Mahogany'] },
//   { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
// ]

要查看可用的完整方法列表,请访问https://collect.js.org

Laravel 集合与 collect.js 之间的区别

虽然 collect.js 提供了与 Laravel 集合(在 PHP 中)相似的 API,但有一些需要注意的差异,这可能让您感到困惑。

Laravel 在使用集合中的项目时默认执行“松散比较”,并提供了一些方法,可用于“严格”类型检查。然而,在 collect.js 中,并没有实现这些额外的“严格”类型检查方法。相反,collect.js 中所有方法(除了 where 方法)都默认执行严格检查。

以下方法在 collect.js 中没有实现

  • containsStrict - 您可以使用 contains 代替
  • duplicatesStrict - 您可以使用 duplicates 代替
  • uniqueStrict - 您可以使用 unique 代替
  • whereStrict - 您可以使用 where 代替
  • whereInStrict - 您可以使用 whereIn 代替
  • whereNotInStrict - 您可以使用 whereNotIn 代替

让我们看看如何使用 where 方法执行严格比较的示例。让我们假设我们想在 Laravel 集合中使用 where 方法。

$users = [
    ['name' => 'Ash', 'is_verified' => false],
    ['name' => 'Daniel', 'is_verified' => true],
    ['name' => 'Taylor', 'is_verified' => 'true'],
    ['name' => 'Jeffrey', 'is_verified' => 1],
];

$filtered = collect($items)->where('is_verified', true);
  
// $filtered would now contain the following items:

// ['name' => 'Daniel', 'is_verified' => true]
// ['name' => 'Taylor', 'is_verified' => 'true']
// ['name' => 'Jeffrey', 'is_verified' => 1]

如您所见,有三项保留,因为 true 严格等于 true,松散等于 "true"1

如果我们想执行严格比较,我们可以使用 whereStrict 方法,如下所示

$users = [
    ['name' => 'Ash', 'is_verified' => false],
    ['name' => 'Daniel', 'is_verified' => true],
    ['name' => 'Taylor', 'is_verified' => 'true'],
    ['name' => 'Jeffrey', 'is_verified' => 1],
];

$filtered = collect($items)->whereStrict('is_verified', true);
  
// $filtered would now contain the following item:

// ['name' => 'Daniel', 'is_verified' => true]

如您所见,我们只留下了一项,因为我们只使用了严格比较。

如果我们想在 collect.js 中使用 where,我们可以写成这样

const items = [
    {name: 'Ash', is_verified: false},
    {name: 'Daniel', is_verified: true},
    {name: 'Taylor', is_verified: 'true'},
    {name: 'Jeffrey', is_verified: 1},
];

const filtered = collect(items).where('is_verified', true);
  
// 'filtered' would now contain the following items:
  
// {name: 'Daniel', is_verified: true}
// {name: 'Taylor', is_verified: 'true'}
// {name: 'Jeffrey', is_verified: 1}

如果我们想进行严格的比较(类似于集合的 whereStrict 方法),则可以这样使用 where 方法

const items = [
    {name: 'Ash', is_verified: false},
    {name: 'Daniel', is_verified: true},
    {name: 'Taylor', is_verified: 'true'},
    {name: 'Jeffrey', is_verified: 1},
];

const filtered = collect(items).where('is_verified', '===', true);
  
// 'filtered' would now contain the following items:
  
// {name: 'Daniel', is_verified: true}

如上例所示,我们已经将 === 传递给方法作为第二个参数,这将在过滤项比较时用作运算符。

结论

希望这篇文章能让您对使用 collect.js 在 JavaScript 中处理数组时的 Laravel-like 语法有一个简要的了解。

如果您喜欢阅读这篇文章,我很乐意听听您的意见。同样,如果您有任何改进未来文章的反馈,我也很乐意听到。

您可能还会对我的225页电子书 "Battle Ready Laravel" 感兴趣,该书更深入地涵盖了类似的主题。

如果您想每次我发布新文章时都收到更新,请随意订阅我的通讯

继续构建精彩的东西! 🚀

最后更新 1 年前。

driesvints 赞同了这篇文章

1
喜欢这篇文章? 让作者知道并给他们“点赞”!
ash-jc-allen (Ash Allen) 我是一位来自英国普雷斯顿的自由职业 Laravel 网络开发人员。我维护 Ash Allen 设计博客,并有幸参与到许多酷和激动人心的项目中 🚀

您可能还会喜欢这些文章

2024年3月11日

如何使用 Larastan 将您的 Laravel 应用从 0 到 9 整理

在 Laravel 应用执行之前找到错误是可能的,多亏了 Larastan...

阅读文章
2024年7月19日

不使用 traits 标准化 API 响应

我注意到,大多数用于 API 响应的库都是使用 traits 实现的,...

阅读文章
2024年7月17日

在您的 Laravel 项目中通过 Discord 通知收集反馈

如何在 Laravel 项目中创建反馈模块,并在接收到消息时收到 Discord 通知...

阅读文章

我们要感谢这些 令人难以置信的公司 对我们的支持

您的标志在这里?

Laravel.io

Laravel 问题解决、知识共享和社区建设的平台。

© 2024 Laravel.io - 版权所有。