0

Update

How to cartesian product object array like this, and dynamic data if have 3 properties and output like below

const property = [
  {
    name: 'color',
    list: [
      { title: 'red', priceIncrease: 2, weightIncrease: 0 },
      { title: 'blue', priceIncrease: 3, weightIncrease: 0 }
    ]
  },
  {
    name: 'size',
    list: [
     { title: 'm', priceIncrease: 3, weightIncrease: 1 },
     { title: 'l', priceIncrease: 4, weightIncrease: 2 },
     { title: 'xl', priceIncrease: 5, weightIncrease: 3 }
    ]
  }
]

// Output

{ title: 'red, m', price: 5, weight: 1 }
{ title: 'red, l', price: 6, weight: 2 }
{ title: 'red, xl', price: 7, weight: 3 }
{ title: 'blue, m', price: 6, weight: 1 }
{ title: 'blue, l', price: 7, weight: 2 }
{ title: 'blue, xl', price: 8, weight: 3 }
Aqlx
  • 1
  • 1

1 Answers1

-1

Second Edit: (after question changed):. Here is my adjusted version of a cartesian function that returns an array with the desired result objects:

const property = [
  {
name: 'color',
list: [
  { title: 'red', priceIncrease: 2, weightIncrease: 0 },
  { title: 'blue', priceIncrease: 3, weightIncrease: 0 }
]
  },
  {
name: 'size',
list: [
 { title: 'm', priceIncrease: 3, weightIncrease: 1 },
 { title: 'l', priceIncrease: 4, weightIncrease: 2 },
 { title: 'xl', priceIncrease: 5, weightIncrease: 3 }
]
  }
]

function cartesian(u,v){
  return u.map(a=> // adjust the following line to perform the operations you desire:
    v.map(b=>({title:a.title+', '+b.title,
               price:a.priceIncrease+b.priceIncrease, 
               weight:a.weightIncrease+b.weightIncrease}))
  )
  // to achieve the format given by OP do:
  .reduce((a,c)=>a.concat(c))
}

console.log(cartesian(property[0].list, property[1].list));
.as-console-wrapper {max-height:100% !important}
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43