Skip to content
Advertisement

How to split an arbitrary JavaScript object in routes, like a tree

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement