如何从嵌套对象中获取具有值的所有键 [英] How to get all keys with values from nested objects

查看:101
本文介绍了如何从嵌套对象中获取具有值的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似Object.keys的东西,但它适用于潜在的嵌套对象.它也不应包含具有对象/数组值的键(它应仅包含具有立即字符串/数字/布尔值的键).

I'm looking for something kind of like Object.keys but that works for potentially nested objects. It also shouldn't include keys that have object/array values (it should only include keys with immediate string/number/boolean values).

{
   "check_id":12345,
   "check_name":"Name of HTTP check",
   "check_type":"HTTP"
}

预期产量

[
  "check_id",
  "check_name",
  "check_type"
]

Object.keys适用于这种扁平情况,但不适用于嵌套情况:

Object.keys would work for flat cases like this, but not for nested cases:

{
   "check_id":12345,
   "check_name":"Name of HTTP check",
   "check_type":"HTTP",
   "tags":[
     "example_tag"
   ],
   "check_params":{
      "basic_auth":false,
      "params":[
        "size"
      ],
      "encryption": {
        "enabled": true,
      }
   }
}

预期产量

[
  "check_id",
  "check_name",
  "check_type",
  "check_params.basic_auth",
  "check_params.encryption.enabled"
]

请注意,这不包括tagscheck_paramscheck_params.paramscheck_params.encryption,因为这些值是数组/对象.

Note that this does not include tags, check_params, check_params.params, or check_params.encryption since these values are arrays/objects.

有没有这样做的图书馆?您将如何实现它以便它可以与任何对象(无论大小,嵌套或小型)一起使用?

Is there a library that does this? How would you implement it so that it can work with any object, large and nested, or small?

推荐答案

您可以像这样使用reduce:

You could use reduce like this:

const keyify = (obj, prefix = '') => 
  Object.keys(obj).reduce((res, el) => {
    if( Array.isArray(obj[el]) ) {
      return res;
    } else if( typeof obj[el] === 'object' && obj[el] !== null ) {
      return [...res, ...keyify(obj[el], prefix + el + '.')];
    } else {
      return [...res, prefix + el];
    }
  }, []);

const input = {
   "check_id":12345,
   "check_name":"Name of HTTP check",
   "check_type":"HTTP",
   "tags":[
     "example_tag"
   ],
   "check_params":{
      "basic_auth":false,
      "params":[
        "size"
      ],
      "encryption": {
        "enabled": true,
        "testNull": null,
      }
   }
};

const output = keyify(input);

console.log(output);

这篇关于如何从嵌套对象中获取具有值的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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