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

如何在JavaScript中生成对象数组的指定格式笛卡尔积

生成属性数组的笛卡尔积

输入数据

const attributes = [
    {
        "name": "Size",
        "values": ["10", "39"]
    },
    {
        "name": "Color",
        "values": ["Yellow", "Pink"]
    },
    {
        "name": "Country",
        "values": ["USA", "UK"]
    }
];

需求

生成上述属性值的笛卡尔积,输出为包含多个子数组的数组,每个子数组对应一组属性组合,每个属性对象包含id(属性在原数组中的索引+1)、name、value字段,结构示例如下:

[
    [
      { id: 1, name: 'Size', value: '10' },
      { id: 2, name: 'Color', value: 'Yellow' },
      { id: 3, name: 'Country', value: 'USA' },
    ],
    // ... 其余组合
];

实现代码

function generateCartesianProduct(attributes) {
    let result = [[]];
    
    attributes.forEach((attr, index) => {
        const temp = [];
        result.forEach(combo => {
            attr.values.forEach(value => {
                temp.push([...combo, {
                    id: index + 1,
                    name: attr.name,
                    value: value
                }]);
            });
        });
        result = temp;
    });
    
    return result;
}

// 调用示例
const attributes = [
    { "name": "Size", "values": ["10", "39"] },
    { "name": "Color", "values": ["Yellow", "Pink"] },
    { "name": "Country", "values": ["USA", "UK"] }
];

const product = generateCartesianProduct(attributes);
console.log(product);

逻辑说明

  1. 初始化结果数组为[[]],作为组合的初始状态
  2. 遍历每个属性,对现有结果中的每一组组合,依次拼接当前属性的每个值对应的对象
  3. 每个属性对象的id取原数组的索引+1,确保和需求中的编号一致
  4. 最终得到所有可能的属性值组合,完全匹配目标结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:23:18