Blog>
Snippets

Deserializing Complex Nested Objects

Illustrate the process of deserializing complex nested objects from URL search parameters into JavaScript objects, using custom deserialization functions with TanStack Router.
function parseNestedObject(searchParams) {
  const result = {};
  // Iterate through each key-value pair in the searchParams
  searchParams.forEach((value, key) => {
    // Split the key by '.' to find nested levels
    const keys = key.split('.');
    let currentLevel = result;

    // Iterate through keys to construct nested object
    keys.forEach((k, index) => {
      // If not the last key, move deeper or create new object
      if (index < keys.length - 1) {
        if (!currentLevel[k]) {
          currentLevel[k] = {};
        }
        currentLevel = currentLevel[k];
      } else {
        // Last key, set the value
        currentLevel[k] = value;
      }
    });
  });
  return result;
}
This function takes URLSearchParams as an input and parses them into a complex nested object. By splitting each key on '.', it constructs a nested structure in the resulting object, assigning the corresponding value to the deepest key.
const searchParams = new URLSearchParams('user.name=John&user.age=30&user.address.city=NYC');
const deserializedObject = parseNestedObject(searchParams);
console.log(deserializedObject);
This is an example usage of the parseNestedObject function. It creates a new URLSearchParams instance with a string that represents some complex, nested query parameters. It then uses parseNestedObject to convert this into a nested JavaScript object and logs the result.