infinitywarior
infinitywarior

Reputation: 379

Make combinations of elements of an array 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 contain key value pairs so that the array elements can be recognized which group they fall into.

I am facing problem in adding keys to the elements generated because m unable to keep track of the object keys

Upvotes: 4

Views: 66

Answers (1)

Faly
Faly

Reputation: 13356

If you can use ES6 (default parameters, spread operator, arrow function, ...), the following code do the job:

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;
}

Upvotes: 5

Related Questions