How can I get an array of all possible combinations of an object's key/values

I have an object:

{
a: 1,
b: "2",
c: "3",
// ...
}

I want to get an array with all possible combinations, as objects, of each key/value pair like this:

[
  { a: 1 },
  { b: "2" },
  { c: "3" },
  { a: 1, b: "2", c: "3" },
  { a: 1, b: "2" },
  { a: 1, c: "3" },
  { b: "2", c: "3" },
  // ...
]

>Solution :

You could treat the object’s keys like a set, and calculate its power set using an algorithm like the one described in this question:

const fn = (o) => {
  const result = [];
  const keys = Object.keys(o);

  for (let i = 0; i < Math.pow(2, keys.length); i++) {
    let current = {};
    
    for (let j = 0; j < keys.length; j++) {
      if ((i & (1 << j)) > 0) {
        current[keys[j]] = o[keys[j]];
      }
    }
    
    result.push(current);
  }
  
  return result;
}

console.log(fn({a: 1, b: '2', c: '3'}));

Leave a Reply