简体   繁体   中英

How to combine arrays of objects according probability in JavaScript?

I have an array with 3 arrays of objects.

[
  [
    {
      VKORG: "3060",
      VTWEG: "AS",
      VRKME: "CX",
      LVORM: ""
    },
    {
      VKORG: "3060",
      VTWEG: "MF",
      VRKME: "CX",
      LVORM: ""
    }
  ],
  [
    {
      MEINH: "CX",
      UMREZ: "12",
      UMREN: "1"
    }
  ],
  [
    {
      WERKS: "3060",
      LGORT: "0011"
    },
    {
      WERKS: "3060",
      LGORT: "HU00"
    }
  ]
]

So I want to combine the objects of each array within them, according the probability of combinations between then... So it should look like this:

[
    {
      VKORG: "3060",
      VTWEG: "AS",
      VRKME: "CX",
      LVORM: "",
      MEINH: "CX",
      UMREZ: "12 ",
      UMREN: "1 ",
      WERKS: "3060",
      LGORT: "0011"
    },
    {
      VKORG: "3060",
      VTWEG: "MF",
      VRKME: "CX",
      LVORM: "",
      MEINH: "CX",
      UMREZ: "12 ",
      UMREN: "1 ",
      WERKS: "3060",
      LGORT: "0011"
    },
    {
      VKORG: "3060",
      VTWEG: "AS",
      VRKME: "CX",
      LVORM: "",
      MEINH: "CX",
      UMREZ: "12 ",
      UMREN: "1 ",
      WERKS: "3060",
      LGORT: "HU00"
    },
    {
      VKORG: "3060",
      VTWEG: "MF",
      VRKME: "CX",
      LVORM: "",
      MEINH: "CX",
      UMREZ: "12 ",
      UMREN: "1 ",
      WERKS: "3060",
      LGORT: "HU00"
    }
  ]
};

How can I do that with JavaScript? I'm spending a lot of time to do that with lodash, but nothing until here.

You could take a standard algorithm for a cartesian product and get joined objects as result.

 var data = [[{ VKORG: "3060", VTWEG: "AS", VRKME: "CX", LVORM: "" }, { VKORG: "3060", VTWEG: "MF", VRKME: "CX", LVORM: "" }], [{ MEINH: "CX", UMREZ: "12", UMREN: "1" }], [{ WERKS: "3060", LGORT: "0011" }, { WERKS: "3060", LGORT: "HU00" }]], result = data.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])).map(a => Object.assign({}, ...a)); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You can create a recursive function with Array.flatMap() , and Array.map() that combines the arrays:

 const cartesian = ([a, ...arrs]) => arrs.length? // if there are more arrays a.flatMap(o1 => cartesian(arrs) // run them through cartesian, and combine with current object.map(o2 => ({...o1, ...o2 })) ): a // return the current array const arrs = [[{ VKORG: "3060", VTWEG: "AS", VRKME: "CX", LVORM: "" }, { VKORG: "3060", VTWEG: "MF", VRKME: "CX", LVORM: "" }], [{ MEINH: "CX", UMREZ: "12", UMREN: "1" }], [{ WERKS: "3060", LGORT: "0011" }, { WERKS: "3060", LGORT: "HU00" }]] const results = cartesian(arrs) console.log(results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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