从 index/keys 数组创建字符串对象路径

Create string object path from array of index/keys

我将 Zod to validate the input of my application forms and when a validation error happens I receive an array of errorsmessage 属性 和 path 属性.

一起使用

我需要将收到的 path 属性 转换为 string 对象路径,以便我可以使用它为 React Final Form 创建 ValidationError

给定 path:

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

预期string对象路径:

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

令人惊讶的是,我没有在 Stack Overflow、Google 搜索或 NPM 上找到实现此代码的任何代码:)

您可以使用Array.reduce来实现您想要的。

const paths = ["company", 0, "name"];

const result = paths.reduce((acc, item) => {
  return typeof item === "string" ?
    acc + "." + item :
    `${acc}[${item}]`

}, "");

console.log(result.slice(1));

快速尝试:

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"]));

编辑:因此,通过查看@vich 的post,我了解到如果您不指定累加器,reduce 会愉快地使用数组的第一个元素作为累加器,所以这里有一个稍微短一些的版本:

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"]));

这很简单。值得你自己去尝试。

["user", "name"].reduce((string, item) => (typeof item === "number") ? string + "[" + item + "]" : string + "." + item)

"user.name"

["company", 0, "name"].reduce((string, item) => (typeof item === "number") ? string + "[" + item + "]" : string + "." + item)

"company[0].name"