You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何将多数组生成全组合并添加指定属性为对象数组?

在Angular中生成多数组的全组合并添加属性

实现思路

核心需求是计算多个数组的笛卡尔积,并为每个组合添加固定的price和Quantity属性。我们可以通过以下步骤实现:

  1. 将每个输入数组转换为键值对形式(键为数组名称,值为元素的name属性)
  2. 迭代计算所有数组的笛卡尔积,合并成完整的组合对象
  3. 为每个组合添加默认的price和Quantity属性

工具函数实现

创建一个通用的工具函数,支持任意数量的输入数组:

// 定义类型增强类型安全
interface OptionItem {
  id: number;
  name: string;
}

interface ProductCombination {
  [key: string]: string | number;
  price: number;
  Quantity: number;
}

export function generateProductCombinations(options: Record<string, OptionItem[]>): ProductCombination[] {
  // 1. 转换每个数组为键值对格式
  const transformedArrays = Object.entries(options).map(([key, items]) => {
    return items.map(item => ({ [key]: item.name }));
  });

  // 2. 计算笛卡尔积
  const product = transformedArrays.length 
    ? transformedArrays.reduce((acc, curr) => {
        return acc.flatMap(prevObj => curr.map(currObj => ({ ...prevObj, ...currObj })));
      }, [{}] as Array<Record<string, any>>)
    : [];

  // 3. 添加默认属性
  return product.map(comb => ({ ...comb, price: 0, Quantity: 0 }));
}

Angular组件中的使用示例

在组件中调用该函数,传入你的数组数据:

import { Component } from '@angular/core';
import { generateProductCombinations } from './utils';

@Component({
  selector: 'app-combination-generator',
  template: `<pre>{{ combinations | json }}</pre>`
})
export class CombinationGeneratorComponent {
  combinations: ProductCombination[];

  constructor() {
    // 示例输入数据
    const color = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}];
    const size = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}];
    // 可扩展更多数组,例如:
    // const material = [{id:1, name: "Cotton"}, {id:2, name: "Polyester"}];

    // 生成组合
    this.combinations = generateProductCombinations({ color, size });
    // 若添加第三个数组:generateProductCombinations({ color, size, material });
  }
}

关键特性说明

  • 灵活性:支持任意数量的输入数组,无需修改核心逻辑
  • 类型安全:通过TypeScript接口定义输入输出类型,避免类型错误
  • 空值处理:若输入数组为空或无输入,返回空数组而非无效对象

内容的提问来源于stack exchange,提问作者Zulfikar Badurdeen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:50:40