获取嵌套对象键作为连接字符串 [英] Get nested objects key as joined string

查看:60
本文介绍了获取嵌套对象键作为连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:

{
  "mobile": "Mob # Required",
  "client": [
    undefined,
    null,
    {
      "usergroup": "Required"
    },
    {
      "id": "Required",
      "usergroup": "Required"
    },
    {
      "id": "Required",
      "usergroup": "Required"
    }
  ]
}

预期输出:

[
    "mobile", 
    "client.2.usergroup", 
    "client.3.id", 
    "client.3.usergroup", 
    "client.4.id", 
    "client.4.usergroup"
]

我在我的项目&中使用Formiks FieldArray;错误对象中的字段名称不是预期的.Object.Keys()在这种情况下不能很好地工作.

I am using Formiks FieldArray in my project & the field name in error object is not what is expected. Object.Keys() doesn't work well for such scenario.

推荐答案

我确定有库可以为您完成此操作,但这是我想出的:

I'm sure there are libraries out there to do this for you, but here is what I came up with:

function flattenNestedObject(input, path) {
  path = path || [];

  return Object.keys(input).reduce(function(arr, key) {
    if (input[key] && typeof input[key] === "object") {
      return arr.concat(flattenNestedObject(input[key], path.concat(key)));
    }

    if (typeof input[key] !== 'undefined' && input[key] !== null) {
      return arr.concat((path.concat(key).join(".")));
    }

    return arr;
  }, []);
}

https://codesandbox.io/s/sweet-jang-j51dh

Object.keys 对您不起作用的原因是,它没有递归获取对象的所有键.另外,在预期的输出中,如果对象包含嵌套的数组或对象,则不希望它的所有键.

The reason Object.keys will not work for you is that it doesn't recursively obtain all keys of an object. Also, in your expected output, you don't want all the keys of an object if it contains nested Arrays or Objects.

这篇关于获取嵌套对象键作为连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆