Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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" },
  // ...
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading