[Vuejs]-JavaScript foreach objects

4👍

Sounds like you want the cartesian product

For your specific case, this is probably what you’re looking for,

addVariant: function (text) {
    let cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())), []);
    
    let values = this.attributes.map(attr => attr.values);
    let combinations = cartesian(...values).map(v => v.join('/'));
    console.log(combinations);
},
👤Shadab

2👍

So basically you want to make combinations of attribute.values right?
Here’s an answer I found for making combinations with arrays of javascripts.
https://stackoverflow.com/a/47701395/13095249
I’m not sure how that works I just copied the code.

Coming back to your problem, I would make an array for all attribute.values like

parts = attributes.map(attribute => attribute.values)

and run the code in above answer should give you the desired output

parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

your addVariant function could look like:

addVariant: function (text) {
  const parts = this.attributes.map(attribute => attribute.values);
  const combinations = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
  console.log(combinations)
},

2👍

You can use array#reduce with array#map and array#flatMap to generate cartesian product of values.

const attributes = [ { "title":{ "text":"Size", "value":"1" }, "values":[ "M", "L", "X" ] }, { "title":{ "text":"Color", "value":"2" }, "values":[ "Red", "Green", "Black" ] }, { "title":{ "text":"Material" }, "values":[ "Cotton", ] } ],
    result = attributes.reduce((r, o, i) => {
      const array = o.values.map(v => v);
      return i ? array.flatMap(v => r.map(w => (w + '\\' + v))): array;
    },[]);
console.log(result.join());
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a comment