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

如何对对象数组执行笛卡尔积运算?支持多属性动态数据处理

实现多属性对象数组的笛卡尔积运算

嘿,我来帮你搞定这个生成属性笛卡尔积的需求!根据你给出的输入和预期输出,我写了一个简单直观的JavaScript函数,能动态处理任意数量(包括3个)的属性,完美生成你要的组合结果。

需求回顾

你需要把每个属性的选项做笛卡尔积组合:

  • 每个组合的title是对应选项title的逗号拼接
  • price是所有选中选项的priceIncrease之和
  • weight是所有选中选项的weightIncrease之和

解决方案代码

const property = [
  { name: 'color', list: [ { title: 'red', priceIncrease: 2, weightIncrease: 0 }, { title: 'blue', priceIncrease: 3, weightIncrease: 0 } ] },
  { name: 'size', list: [ { title: 'm', priceIncrease: 3, weightIncrease: 1 }, { title: 'l', priceIncrease: 4, weightIncrease: 2 }, { title: 'xl', priceIncrease: 5, weightIncrease: 3 } ] }
];

function calculateCartesianProduct(properties) {
  // 处理边界情况:如果没有属性,直接返回空数组
  if (!properties.length) return [];

  // 初始化结果:先把第一个属性的选项转换成目标格式
  let result = properties[0].list.map(item => ({
    title: item.title,
    price: item.priceIncrease,
    weight: item.weightIncrease
  }));

  // 遍历剩余的每个属性,逐步构建笛卡尔积
  for (let i = 1; i < properties.length; i++) {
    const currentProperty = properties[i];
    const tempResults = [];

    // 将现有结果与当前属性的每个选项进行组合
    result.forEach(existingCombo => {
      currentProperty.list.forEach(option => {
        tempResults.push({
          title: `${existingCombo.title}, ${option.title}`,
          price: existingCombo.price + option.priceIncrease,
          weight: existingCombo.weight + option.weightIncrease
        });
      });
    });

    // 更新结果为新的组合集合
    result = tempResults;
  }

  return result;
}

// 执行函数并输出结果
const cartesianCombos = calculateCartesianProduct(property);
console.log(cartesianCombos);

代码逻辑说明

  1. 边界处理:先判断如果传入的属性数组为空,直接返回空数组,避免报错。
  2. 初始化结果:把第一个属性的每个选项转换成我们需要的输出格式,作为初始的组合集合。
  3. 迭代构建笛卡尔积:从第二个属性开始,遍历现有所有组合,再和当前属性的每个选项一一配对,生成新的组合。每次配对时:
    • 拼接两个选项的title
    • 累加priceIncrease得到组合的price
    • 累加weightIncrease得到组合的weight
  4. 动态适配属性数量:不管你是2个、3个还是更多属性,这个函数都能自动处理,完全不需要修改核心逻辑。

比如如果再加一个material属性:

const property = [
  // 原有的color、size属性...
  { name: 'material', list: [ { title: 'cotton', priceIncrease: 1, weightIncrease: 0.5 }, { title: 'polyester', priceIncrease: 0, weightIncrease: 0.3 } ] }
];

函数会自动生成color + size + material的所有6×2=12种组合,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:02:54