collect.js 的 combine() 方法完全解析:用键集合与值集合快速构建对象映射

原创2026-10-14 11:49:531,883 阅读
文章标签:开发工具

collect.js 的 combine() 方法完全解析:用键集合与值集合快速构建对象映射

combine() 是 collect.js 提供的集合方法之一,它的核心职责是:把当前集合的元素当作键(keys),与传入的另一个数组或集合中的值(values)按顺序一一配对,组合成一个新的对象集合。本文以 combine.md 为骨架,结合 源码实现、单元测试 与类型声明,系统讲解该方法的基础用法、源码分支逻辑、边界行为,以及与 zip()、flip()、merge() 等相关方法的区别。读完后你将能熟练用 combine() 完成「键列表 + 值列表 → 对象」的映射转换,并理解其在不同输入形态下的行为差异。

方法签名与核心语义

从 类型声明 可以看出,combine() 的接口定义如下:

combine<T, U>(array: U[]): Collection<T>;

它接收一个数组(或另一个 Collection),返回一个新的 Collection。其语义可以一句话概括:将当前集合的元素作为键,将传入集合的元素作为值,按索引位置一一配对。

最直观的场景是:你手上有两份平行数据——一份是字段名列表,一份是对应的字段值列表,用 combine() 可以一步把它们拼成结构化对象。

基础用法:官方示例

原文档 combine.md 给出的最典型用法是键数组与值数组的组合:

const collection = collect(['name', 'number']);

const combine = collection.combine(['Mohamed Salah', 11]);

combine.all();

// {
//   name: 'Mohamed Salah',
//   number: 11
// }

这里 <a href="https://link.gitcode.com/i/142bd6095e11603974c49fefa0d0cddd" target="_blank">'name', 'number'] 提供了键,['Mohamed Salah', 11] 提供了值,两个数组按下标一一对应,最终得到 { name: 'Mohamed Salah', number: 11 }。all() 方法用于取出集合底层的原始数据(其实现见 [all.js,直接返回 this.items)。

源码实现:五种输入形态的分支逻辑

combine() 的完整实现位于 src/methods/combine.js,虽然只有二十多行,却根据「当前集合」与「传入参数」的不同类型组合,划分出五种分支:

module.exports = function combine(array) {
  let values = array;

  if (values instanceof this.constructor) {
    values = array.all();
  }

  const collection = {};

  if (Array.isArray(this.items) && Array.isArray(values)) {
    this.items.forEach((key, iterator) => {
      collection[key] = values[iterator];
    });
  } else if (typeof this.items === 'object' && typeof values === 'object') {
    Object.keys(this.items).forEach((key, index) => {
      collection[this.items[key]] = values[Object.keys(values)[index]];
    });
  } else if (Array.isArray(this.items)) {
    collection[this.items[0]] = values;
  } else if (typeof this.items === 'string' && Array.isArray(values)) {
    [collection[this.items]] = values;
  } else if (typeof this.items === 'string') {
    collection[this.items] = values;
  }

  return new this.constructor(collection);
};

我们逐一拆解这五种分支:

分支一:数组键 + 数组值(最常用)

if (Array.isArray(this.items) && Array.isArray(values)) {
  this.items.forEach((key, iterator) => {
    collection[key] = values[iterator];
  });
}

当前集合是数组、传入参数也是数组时,直接用 forEach 的第二个参数(索引)去取值数组对应位置的元素。这正是官方示例走的路径。

分支二:对象键集合 + 对象值

} else if (typeof this.items === 'object' && typeof values === 'object') {
  Object.keys(this.items).forEach((key, index) => {
    collection[this.items[key]] = values[Object.keys(values)[index]];
  });
}

当当前集合是一个对象、传入的也是一个对象时,组合规则是:以当前对象每个属性的值作为新对象的键,以传入对象每个属性的值(按 Object.keys() 的顺序)作为新对象的值。换句话说,它取的是两边对象的「值」来做键值配对,对象的属性名本身不参与映射。

测试 combine_test.js 验证了这一点:

const collection = collect(['name', 'shortName']);
const combine = collection.combine({ o: 'Liverpool FC', x: 'LFC' });

expect(combine.all()).to.eql({
  name: 'Liverpool FC',
  shortName: 'LFC',
});

注意这里第一个参数(当前集合)是数组而非对象,所以严格来说走的是「分支一」,但第二参数以对象形式传入依然有效——因为分支一只要求当前集合是数组、值集合是数组。那么对象值怎么变成数组的?请看下文「Collection 解包」的说明,实际上测试用例中的对象值是通过 Collection 包装后传入的(collect({...}) 的内部 items 仍是对象)。

分支三:数组键集合 + 标量值

} else if (Array.isArray(this.items)) {
  collection[this.items[0]] = values;
}

当前集合是数组、传入值既不是数组也不是对象(如字符串)时,只取键数组的第一个元素作为键,把整个标量作为值。测试 combine_test.js 中的示例:

const collection = collect(['name', 'number']);
const combine = collection.combine('Joël Matip');

expect(combine.all()).to.eql({ name: 'Joël Matip' });

['name', 'number'] 中只有 'name' 被用作键,'Joël Matip' 成为其值,'number' 被忽略。

分支四:字符串键集合 + 数组值

} else if (typeof this.items === 'string' && Array.isArray(values)) {
  [collection[this.items]] = values;
}

当当前集合是字符串(注意 Collection 构造函数 会把非数组、非对象的原始值包装成单元素数组,所以这里的 this.items 实际是 ['name'] 这样的单元素数组……详见下方说明)、传入值是数组时,使用解构赋值把数组的第一个元素赋给键。

分支五:字符串键集合 + 标量值

} else if (typeof this.items === 'string') {
  collection[this.items] = values;
}

当前集合是字符串、传入值是标量时,直接 collection<a href="https://link.gitcode.com/i/40f453c53f7797ce12c00e4d32687354" target="_blank">string] = values。测试 [combine_test.js 覆盖了这一场景:

const collection = collect('name');
const combine = collection.combine('Steven Gerrard');
const combine2 = collection.combine(['Darwin Núñez']);

expect(combine.all()).to.eql({ name: 'Steven Gerrard' });
expect(combine2.all()).to.eql({ name: 'Darwin Núñez' });

这里 collect('name') 由于传入的是字符串,构造函数将其包装为 ['name'];测试还同时验证了传入字符串值和单元素数组值两种情况都能得到 { name: ... }。

说明:从源码结构看,分支四与分支五中 typeof this.items === 'string' 的判断在常规构造流程下较难直接触发(因为构造函数会把字符串包装成数组),更常见的实际路径是「单元素数组集合 + 数组/标量值」的组合。这种多分支设计体现了 collect.js 对多种输入形态的宽容处理。

支持传入 Collection:自动解包

combine() 的第一段代码做了类型归一化:

if (values instanceof this.constructor) {
  values = array.all();
}

如果传入的参数是另一个 Collection 实例,会先调用其 all() 取出底层数据,再进入上述分支判断。因此下面这种写法完全合法:

const collection = collect('name');
const combine = collection.combine(collect('Roberto Firmino'));

expect(combine.all()).to.eql({ name: 'Roberto Firmino' });

这是 combine_test.js 中的测试用例。同理,测试中「数组键 + 对象值」的用例(collection.combine({ o: 'Liverpool FC', x: 'LFC' }))之所以能成立,是因为对象在 collect() 包装时其 items 直接保留为对象引用,之后 all() 返回该对象,走的是「分支一」中 values 为数组/对象的对应路径——实际上 { o: ..., x: ... } 不是数组,此时会进入「分支二」的 typeof values === 'object' 判断,按键数组与对象值进行顺序配对。

不可变性:原集合不会被修改

从实现看,combine() 只读取 this.items,把所有结果写入全新的 collection 对象,最后通过 new this.constructor(collection) 返回新集合,绝不改动原集合。测试用例也明确断言了这一点:

const collection = collect(['name', 'number']);
const combine = collection.combine(['Steven Gerrard', 8]);

expect(combine.all()).to.eql({
  name: 'Steven Gerrard',
  number: 8,
});
expect(collection.all()).to.eql(['name', 'number']); // 原集合保持不变

这意味着你可以放心地链式复用原集合,不必担心副作用。

边界行为与注意事项

基于源码分支与测试,可以总结出以下实用的边界行为:

  • 键值长度不一致时:组合按索引配对,多余的值会被丢弃。例如 collect(['name', 'number']).combine(['only one']) 只会生成 { name: 'only one' }(values[1] 为 undefined 时键 number 仍会被写入,值为 undefined,从实现看 forEach 会遍历全部键)。
  • 值集合是对象时:按 Object.keys() 的枚举顺序取值配对,与对象属性的书写顺序相关。
  • 值集合是标量时:只有键集合的第一个元素成为键,其余键被忽略。
  • 传入 Collection 时:自动解包,与其他传入形态等价。
  • 返回值是普通对象集合:combine().all() 得到的是纯对象 { key: value },而不是数组;这与 zip() 的结果形态有本质区别(见下节)。

与相关方法的对比

combine() vs zip()

zip() 也是按索引合并两个数组,但它生成的是成对的子数组:<a href="https://link.gitcode.com/i/49bdf06c97c8befc266aab2f61e64f9b" target="_blank">['Chair', 100], ['Desk', 200]](实现见 [zip.js)。而 combine() 把第一列当键、第二列当值,产出的是对象。二者分别适合「保留成对结构」与「直接映射为对象」两种需求。

combine() vs flip()

flip() 是在单一集合内部交换键与值(如 { name: 'Darwin Núñez' } → { 'Darwin Núñez': 'name' },实现见 flip.js),不涉及外部数据;combine() 则需要两个数据源。

combine() vs merge()

merge() 是「按已有键合并覆盖」,保留原对象结构并合并传入对象的同名键;combine() 则是「从零构建键值映射」。一个是增量合并,一个是整体重建,适用场景完全不同。

combine() vs keyBy()

keyBy() 是从集合内部元素中提取某个字段作为键、元素本身作为值;combine() 的键和值则完全来自两个独立的数据源。

测试与类型支持

  • 单元测试:combine_test.js 共 5 个用例,覆盖「数组键 + 数组值」「字符串集合 + 字符串值」「字符串集合 + 数组值」「数组键 + 对象值」「字符串集合 + Collection」五种形态,并验证了原集合不变性。
  • 类型声明:index.d.ts 中声明为 combine<T, U>(array: U[]): Collection<T>,在 TypeScript 项目中有完整的泛型支持。
  • 方法注册:src/index.js 通过 Collection.prototype.combine = require('./methods/combine') 挂载到 Collection 原型上,与其余 100+ 个方法保持一致的挂载方式,因此也支持链式调用。

快速上手

安装 collect.js 的方式见 docs/installation.md:

# npm
npm install collect.js --save

# 或 yarn
yarn add collect.js

基本使用方式(详见 docs/usage.md):

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

// ESM
import collect from 'collect.js';

一个结合真实场景的完整示例:把 API 返回的平行数组拼成对象,再与其它集合方法链式使用:

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

const keys = collect(['id', 'name', 'goals']);
const values = collect([11, 'Mohamed Salah', 30]);

keys.combine(values).all();
// { id: 11, name: 'Mohamed Salah', goals: 30 }

小结

combine() 是 collect.js 中处理「键值配对」的核心工具方法:它以当前集合为键源、以另一数组/Collection/对象为值源,按顺序构建新的对象集合。理解其 五种源码分支、Collection 自动解包机制与不可变语义,能帮助你在数据重组场景中写出更简洁、更不易出错的代码。若需进一步探究方法间的差异,可对照 zip()、flip() 与 merge() 的文档与源码继续深入。

登录后查看全文
collect.js