如何基于父对象与多值属性集生成全属性组合的子对象?
实现属性值全组合生成子对象的JavaScript方案
原始数据
var parent = { 'Name': 'Product ABC', } var attributes = { // AttributeId : 对应属性值列表 'ID0001': ['Black', 'Red'], 'ID0002': ['Small', 'Medium', 'Large'], 'ID0003': ['Cotton', 'Len'] }
需求说明
需要克隆父对象生成多个子对象,每个子对象保留父对象原有字段,同时新增Attributes数组,该数组由属性集中所有属性值的唯一全组合构成,每个组合对应一个子对象。
实现代码
// 1. 将属性对象转换为结构化数组,方便后续处理 const attributeEntries = Object.entries(attributes).map(([id, values]) => ({ attributeId: id, values })); // 2. 生成属性值的笛卡尔积(所有可能的组合) function generateCartesianProduct(attrList) { return attrList.reduce((result, currentAttr) => { return result.flatMap(existingCombination => { return currentAttr.values.map(val => [ ...existingCombination, { attributeId: currentAttr.attributeId, value: val } ]); }); }, [[]]); } // 3. 结合父对象生成所有子对象 const productVariants = generateCartesianProduct(attributeEntries).map(attrs => { return { ...parent, // 克隆父对象的所有字段 Attributes: attrs }; }); // 查看结果 console.log(productVariants);
代码说明
- 属性结构转换:用
Object.entries拆解原属性对象,再映射成包含attributeId和对应值列表的对象数组,明确每个属性的标识和可选值。 - 笛卡尔积生成:通过
reduce和flatMap嵌套遍历,逐步构建所有属性值的组合,每个组合直接对应Attributes数组的结构。 - 子对象生成:遍历每个属性组合,用扩展运算符克隆父对象,再添加
Attributes字段,得到最终的子对象列表。
内容的提问来源于stack exchange,提问作者Ryan can fly
相关产品推荐
相关产品推荐

