如何从对象数组中的嵌套数组中获取数组值的组合

时间:2019-07-10 13:39:41

标签: javascript arrays vue.js math combinations

我有一个具有以下结构的对象数组:

 var varientSections = [
  {
    type: "frame",
    values: ["black", "white", "wood"]
  },
  {
    type: "finish",
    values: ["matte", "glossy"]
  }
];

我想获取数组值的组合并使用它创建一个新列表。 现在,我能够使用称为 getCombination(varientSections)的方法从嵌套数组值中检索组合。但是,我不知道如何使用以下结构创建新列表:

var results = [
  {
    attributes: [
      {
        type: "frame",
        value: "black"
      },
      {
        type: "finish",
        value: "matte"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "black"
      },
      {
        type: "finish",
        value: "glossy"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "white"
      },
      {
        type: "finish",
        value: "matte"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "white"
      },
      {
        type: "finish",
        value: "glossy"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "wood"
      },
      {
        type: "finish",
        value: "matte"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "wood"
      },
      {
        type: "finish",
        value: "glossy"
      }
    ]
  }
];

下面是我的代码:

function getCombinations(arr) {
  if (arr.length === 0) {
    return [[]];
  }

  let [current, ...rest] = arr;
  let combinations = getCombinations(rest);

  var result = current.values.reduce(
    (accumulator, currentValue) => [
      ...accumulator,
      ...combinations.map(c => [currentValue, ...c])
    ],
    []
  );
  console.log("result is ");
  console.log(result);
  return result;
}

let varientCombinations = getCombinations(varientSections);
console.log(varientCombinations);

let updatedVarientDetails = [];
varientSections.forEach((varientSection, index) => {
  let type = varientSection.type;
  varientCombinations.forEach(combination => {
    let obj = [
      {
        type: type,
        value: combination[index]
      },
    ];
    updatedVarientDetails.push(obj);
  });
});

console.log(updatedVarientDetails);

2 个答案:

答案 0 :(得分:4)

您可以获取笛卡尔积,并在以后提供所需的样式。名称和值取自移交的对象。

该算法采用所有键/值对,并对值具有严格的视图,这意味着如果找到了数组或对象,则w && typeof w === "object"的实际部分将用于添加其他键/值对。

例如具有两个属性的小对象

{ a: 1, b: [2, 3] }

收益

[
    { a: 1, b: 2 },
    { a: 1, b: 3 }
]

更高级的对象,例如

{ a: 1, b: { c: { d: [2, 3], e: [4, 5] } } }

与给定的结构相同

[
    {
        a: 1,
        b: {
            c: { d: 2, e: 4 }
        }
    },
    {
        a: 1,
        b: {
            c: { d: 2, e: 5 }
        }
    },
    {
        a: 1,
        b: {
            c: { d: 3, e: 4 }
        }
    },
    {
        a: 1,
        b: {
            c: { d: 3, e: 5 }
        }
    }
]

这意味着,从找到的所有子对象中获取笛卡尔乘积并将其与实际值组合。

const
    getCartesian = object => Object.entries(object).reduce(
        (r, [key, value]) => {
            let temp = [];
            r.forEach(s =>
                (Array.isArray(value) ? value : [value]).forEach(w =>
                    (w && typeof w === "object" ? getCartesian(w) : [w]).forEach(x =>
                        temp.push({ ...s, [key]: x })
                    )
                )
            );
            return temp;
        },
        [{}]
    ),
    data = [{ type: "frame", value: ["black", "white", "wood"] }, { type: "finish", value: ["matte", "glossy"] }],
    result = getCartesian(data)
        .map(o => ({ attributes: Object.assign([], o).map(({ ...o }) => o) }));

console.log(result);

console.log(getCartesian({ a: 1, b: { c: { d: [2, 3], e: [4, 5] } } }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)

您可以简化为:

var variantSections = [
  {
    type: "frame",
    values: ["black", "white", "wood"]
  },
  {
    type: "finish",
    values: ["matte", "glossy"]
  }
];

// iterate through each variantSection and create objects like {"type": "frame", "value": "black"}
var sections = variantSections.map(variant => {
	return variant.values.map(val => ({type: variant.type, value: val}))
});

// then iterate through the two resulting arrays of objects, combining each into the attributes object you want
var results = [];
for (var i = 0; i < sections[0].length; i++) {
	for (var j = 0; j < sections[1].length; j++) {
		results.push({attributes: [sections[0][i], sections[1][j]]});
	}
}

console.log(JSON.parse(JSON.stringify(results)));