简体   繁体   English

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

[英]Cartesian array based on array of objects in Javascript

I'm looking for method to find cartesian array based on array of objects.我正在寻找基于对象数组查找笛卡尔数组的方法。

Basicly I've seen solutions like that:基本上我见过这样的解决方案:

Cartesian product of multiple arrays in JavaScript JavaScript 中多个数组的笛卡尔积

but I'm not sure how to modify it to work on object property (in my case on property "value").但我不确定如何修改它以处理对象属性(在我的例子中是属性“值”)。

For instance my input:例如我的输入:

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"
  }
];

Expected output:预期输出:

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"
    }
  ]
];

Just take the single arrays as items of a collection of this arrays and perform the algorithm on this data set.只需将单个数组作为该数组集合的项目,并在该数据集上执行算法。

 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM