Skip to content
Advertisement

Write nested map function

I have an object like this:

const object = {
detectors: [1, 2],
  responders: [4, 22],
  activators: [5, 23, 31],
  enablers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
  upgraders: [14, 15, 16, 17, 18, 19, 20, 21, 22],
  catalyzer: [12, 29],
  chains: [27],
  trappers: [13],
  finishers: [16],
}

Expected output :

[
{
    'detectors': 1,
    'responders': 4,
    'activators': 5,
    'enablers': 1,
    'upgraders': 23,
    'catalyzer': 12,
    'chains': 27,
    'trappers': 13,
    'finishers': 16,
},
{
    'detectors': 2,
    'responders': 4,
    'activators': 5,
    'enablers': 1,
    'upgraders': 23,
    'catalyzer': 12,
    'chains': 27,
    'trappers': 13,
    'finishers': 16,
},
{
    'detectors': 1,
    'responders': 22,
    'activators': 5,
    'enablers': 1,
    'upgraders': 23,
    'catalyzer': 12,
    'chains': 27,
    'trappers': 13,
    'finishers': 16,
},
{...

And I already wrote a function like this:

object.activators.map((activator, i) => {
  return object.detectors.map((detector, i) => {
    return object.responders.map((responder, i) => {
      return {
        detectors: detector,
        responders: responder,
        activators: activator,
      };
    });
  });
});

I can write another function to flatten the output of the code above, but is there any other way to write the code above into a more general function (not hardcoded) that can apply to any object?

Advertisement

Answer

You can use a recursive function to get all permutations from the entries.

const object = {
  detectors: [1, 2, 3],
  responders: [4, 22],
  activators: [1, 2, 3, 4]
};
const getPermutations = obj => {
    const res = [];
    const entries = Object.entries(obj);
    const go = (curr, idx) => {
    const key = entries[idx][0];
    for(const val of entries[idx][1]){
      const next = {...curr, [key]: val};
      if(idx !== entries.length - 1) go(next, idx + 1);
      else res.push(next);
    }
  };
  go({}, 0);
  return res;
}
console.log(getPermutations(object));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement