Search code examples
javascripttypescriptreact-final-formzod

Create string object path from array of index/keys


I'm using Zod to validate the input of my application forms and when a validation error happens I receive an array of errors with a message property and a path property.

I need to transform the received path property to a string object path so I can use it to create a ValidationError for React Final Form.

Given path:

["user", "name"]
["company", 0, "name"]

Expected string object path:

"user.name"
"company[0].name"

Surprisingly I didn't find any code on Stack Overflow, Google Search or NPM that implements this :)


Solution

  • A quick attempt:

    const string_path = (path) =>
      path.reduce(
        (acc, item) => acc + (Number.isInteger(item) ? '[' + item + ']' : '.' + item),
        ''
      ).substring(1);
    
    console.log(string_path(["user", "name"]));
    console.log(string_path(["company", 0, "name"]));

    Edit: So, from looking at @vich's post I learned that reduce will happily use the first element of the array as the accumulator if you don't specify one, so here's a slightly shorter version:

    const string_path = (path) =>
      path.reduce(
        (acc, item) => acc + (Number.isInteger(item) ? '[' + item + ']' : '.' + item)
      );
    
    console.log(string_path(["user", "name"]));
    console.log(string_path(["company", 0, "name"]));
    console.log(string_path(["user"]));