基于Javascript中对象数组的笛卡尔数组

时间:2018-11-13 09:22:11

标签: javascript

我正在寻找一种基于对象数组的笛卡尔数组的方法。

基本上我已经看到类似的解决方案:

Cartesian product of multiple arrays in JavaScript

但是我不确定如何修改它以在对象属性上工作(在我的例子中是在属性“值”上)。

例如我的输入:

let arr1 = [
  {
    id: 1,
    type: "attribute",
    value: "arr1-attr1"
  },
  {
    id: 2,
    type: "attribute",
    value: "arr1-attr2"
  }
];

let arr2 = [
  {
    id: 3,
    type: "attribute",
    value: "arr2-attr1"
  }
];

let arr3 = [
  {
    id: 4,
    type: "attribute",
    value: "arr3-attr1"
  },
  {
    id: 5,
    type: "attribute",
    value: "arr3-attr2"
  }
];

预期输出:

output = [
  [
    {
      id: 1,
      type: "attribute",
      value: "arr1-attr1"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 4,
      type: "attribute",
      value: "arr3-attr1"
    }
  ],
  [
    {
      id: 2,
      type: "attribute",
      value: "arr1-attr2"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 5,
      type: "attribute",
      value: "arr3-attr2"
    }
  ],
  [
    {
      id: 1,
      type: "attribute",
      value: "arr1-attr1"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 4,
      type: "attribute",
      value: "arr3-attr1"
    }
  ],
  [
    {
      id: 2,
      type: "attribute",
      value: "arr1-attr2"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 5,
      type: "attribute",
      value: "arr3-attr2"
    }
  ]
];

1 个答案:

答案 0 :(得分:1)

只需将单个数组作为此数组的集合的项,然后对该数据集执行算法即可。

var arr1 = [{ id: 1, type: "attribute", value: "arr1-attr1" }, { id: 2, type: "attribute", value: "arr1-attr2" }],
    arr2 = [{ id: 3, type: "attribute", value: "arr2-attr1" }],
    arr3 = [{ id: 4, type: "attribute", value: "arr3-attr1" }, { id: 5, type: "attribute", value: "arr3-attr2" }],
    result = [arr1, arr2, arr3]
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }