Cartesian of object arrays

by Mubasshir Pawle

JavaScript

getProcessedParams = (paramAttributes, current = []) => {
  // null check
  if (!paramAttributes || !Object.keys(paramAttributes).length) {
    return [];
  }
  const attributeIds = Object.keys(paramAttributes);
  // get current processing attribute
  const attributeId = attributeIds[0]
  const attributesValueIds = paramAttributes[attributeId];
  // keep only remaing
  const remaining = Object.fromEntries(Object.entries(paramAttributes).slice(1));
  const remainingLength = Object.keys(remaining).length;
  // result
  let result = [];
  // loop over attribute value id & add 
  attributesValueIds.forEach((attributesValueId, index) => {
    // make shallow copy
    let newCurrent = current.slice(0);
    // push
    newCurrent.push(attributesValueId);
    // check if more attributeValueIds of another attribute can be added
    if (remainingLength) {
      const resultOfRemaining = getProcessedParams(remaining, newCurrent);
      // merge with current result
      result = result.concat(resultOfRemaining);
    } else {
      // to result to create array of attributesValues
      result.push(newCurrent);
    }
  })

  return result;
}
const params = {
  "attributesValueId": {
    "5": [13, 14, 15],
    "6": [22, 23],
    "7": [28]
  }
}
console.log(getProcessedParams(params.attributesValueId))