-2

Im receiving a set of filters as a composed object in my express server. In order to create the query I came to the conclusion of splitting each object route into a separate array of keys.

Example:

$and: {
    age: [21, 22],
    name: {
        $like: "Alice"
    }
 }

What I want:

[$and,age,[21, 22]]
[$and,name,$like,"Alice"]

Any clue in solving this problem would be much appreciated.

Lazt Omen
  • 40
  • 1
  • 7
  • 1
    did you mean `["$and","age",[21, 22]]` and `["$and","name","$like","Alice"]` - because that would be possible, your thing is not – Bravo Jul 27 '21 at 22:16
  • Have a look at https://stackoverflow.com/a/19101235/1048572 - the output format is not exactly the same, but you'll need to use the same approach – Bergi Jul 27 '21 at 23:03
  • This doesn't need "more focus", there is only one queston. Learn your close reasons!! – Dexygen Jul 27 '21 at 23:19
  • @Dexygen A single question still can be too broad to answer – Bergi Jul 27 '21 at 23:47
  • @Bergi How? Not per the needs more focus close reason description – Dexygen Jul 27 '21 at 23:58

1 Answers1

0

This should work. It uses a recursive function to go through each item of the object and make a route for each value.

const obj = {
  $and: {
    age: [21, 22],
    name: {
      $like: "Alice"
    }
  }
};

function getRoute(o) {
  const result = [];
  const route = (subObj, keyIndex = 0, path = []) => {
    const keys = Object.keys(subObj);
    if (typeof subObj === 'object' && !Array.isArray(subObj) && keys.length > 0) {
      while (keyIndex < keys.length) {
        route(subObj[keys[keyIndex]], 0, [...path, keys[keyIndex]]);
        keyIndex++;
      }
    } else {
      result.push([...path, subObj]);
    }
  };
  route(o);
  return result;
}

console.log(JSON.stringify(getRoute(obj))); // Returns an string
console.log(getRoute(obj)); // Returns an array
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
  • Thanks a lot, you just made my day. I've spent a lot of hours trying to achieve exactly that. I'm still overwhelmed about how much I don't know about JavaScript. – Lazt Omen Jul 28 '21 at 01:24