【问题标题】:Create string object path from array of index/keys从索引/键数组创建字符串对象路径
【发布时间】:2020-11-04 20:46:58
【问题描述】:

我正在使用Zod 来验证我的申请表的输入,当发生验证错误时,我会收到一个errors 数组,其中包含message 属性和path 属性。

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

给定path

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

预期的string 对象路径:

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

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

【问题讨论】:

  • 似乎一个非常简单的循环可以工作。跳过第一个值;如果当前值为字符串,则添加 . 并附加当前值。如果当前值为数字,则添加[、当前值和]。继续遍历数组。
  • 如果您将它们转换为 user['name']company['0']['name'] 会容易得多 - 更少(没有)需要处理的边缘情况。
  • 是的,我会担心这里有更多的边缘情况。任何字符串都可以是属性键,即使是无效的 JS 标识符。
  • @jcalz 很抱歉直接对你发表评论,但我想你可能有兴趣看到stackoverflow.com/q/64676046/251311

标签: javascript typescript react-final-form zod


【解决方案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 的帖子,我了解到如果你不指定一个,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"]));

【讨论】:

    【解决方案2】:

    你可以使用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));

    【讨论】:

      【解决方案3】:

      这很简单。值得您自己尝试。

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

      “用户名”

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

      “公司[0].名称”

      【讨论】:

      • 感谢您的回答!是的,这很简单,但我不确定所有的边缘情况,所以这就是为什么我最终决定向 SO 询问。无论如何,我决定采用@zerkms 评论的方法,因为它让我对代码更有信心。
      猜你喜欢
      • 2014-05-09
      • 2018-03-08
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多