Creating combinations of array elements inside an object

trialObject : {
        'color': ['red','blue'],
        'size': ['s','m'],
        'material': ['cotton']
      }

// RECURSION FUNCTION TO MAKE COMBINATIONS

makeObjectVariants(selected){

      let key = Object.keys(selected)
      if(Object.keys(selected).length === 1){
        return selected[key[0]];
      } else {
        var result = [];
        var currentArray  = selected[key[0]]
        delete selected[key[0]] 
        var restObjects = this.makeObjectVariants(selected) // call function again

        for(var i = 0; i < restObjects.length; i++){
          for (var j = 0; j < currentArray.length; j++) {
            result.push([restObjects[i] +','+ currentArray[j]]);
          }
        }
        return result; // resultant array
      }
    }

// OUTPUT 
0:["cotton,s,red"]
1:["cotton,s,blue"]
2:["cotton,m,red"]
3:["cotton,m,blue"]

// EXPECTED OUTPUT 
[{'material':cotton,'size':s,'color':red},...]

I want the output to have pairs of key values ​​so that the elements of the array can be recognized in which group they fall into.

I have to deal with the problem of adding keys to generated elements, because m cannot track object keys

+4
source share
1 answer

If you can use ES6 (default parameters, distribution operator, arrow function, ...), the following code performs the following task:

var trialObject  = {
    color: ['red','blue'],
    size: ['s','m'],
    material: ['cotton']
};

var result = buildCombinations(trialObject);

console.log(result); 

function buildCombinations(trialObject , keys = Object.keys(trialObject ), keyIndex = 0 , subObj = {}, res = []) {
    trialObject[keys[keyIndex]].forEach(element => {
        subObj[keys[keyIndex]] = element;
        keys[keyIndex + 1] ? buildCombinations(trialObject , keys, keyIndex + 1, subObj, res) : res.push({...subObj});
    });
    return res;
}
Run code
+5
source

Source: https://habr.com/ru/post/1691775/


All Articles