获取嵌套对象键作为连接字符串

时间:2019-12-20 13:11:12

标签: javascript formik

输入:

{
  "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()在这种情况下不能很好地工作。

2 个答案:

答案 0 :(得分:2)

您可以flatMap对象的键。如果当前键的值是一个对象,请使用更新的前缀递归调用getKeys函数。如果不是,请使用给定的前缀返回当前密钥。使用flatMap来获取键的展平数组而不是嵌套数组

const input={mobile:"Mob # Required",client:[{usergroup:"Required"},{id:"Required",usergroup:"Required"},{id:"Required",usergroup:"Required"}]};

const getKeys = (o, prefix = '') =>
  Object.keys(o).flatMap(k =>
    Object(o[k]) === o[k] ? getKeys(o[k], `${prefix}${k}.`) : [prefix + k]
  )

console.log(getKeys(input))

如果不支持flatMap,则可以用相似的逻辑reduce对象的键

const input={mobile:"Mob # Required",client:[{usergroup:"Required"},{id:"Required",usergroup:"Required"},{id:"Required",usergroup:"Required"}]};

function getKeys(o, prefix = '') {
  return Object.keys(o).reduce((acc, k) => {
    if (Object(o[k]) === o[k])
      acc.push(...getKeys(o[k], `${prefix}${k}.`))
    else
      acc.push(prefix + k)
    return acc;
  }, [])
}

console.log(getKeys(input))

答案 1 :(得分:0)

我敢肯定有一些库可以为您做这件事,但这是我想出的:

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对您不起作用的原因是,它没有递归获取对象的所有键。另外,在预期的输出中,如果对象包含嵌套的数组或对象,则不需要所有的键。