递归地遍历对象

如何解决递归地遍历对象

我试图编写一个递归函数来遍历一个对象并根据ID返回项目。我可以使它的第一部分开始工作,但是我很难尝试以递归的方式获得此功能,并且可能会使用新的眼睛。代码如下。当您运行代码段时,您将得到一个包含6个项目的数组,这些数组是我想要的第一次迭代,但是如何调用具有适当参数的函数来获取嵌套项目呢?我的最终目标是将所有以“ Cstm”开头的对象(也嵌套的)添加到tablesAndValues数组中。我试图在此之后对代码进行建模:Get all key values from multi level nested array JavaScript,但这处理的是对象数组,而不是对象的对象。我能得到的任何提示或技巧都非常感谢。

JSFiddle:https://jsfiddle.net/xov49jLs/

const response = {
  "data": {
    "Cstm_PF_ADG_URT_Disposition": {
      "child_welfare_placement_value": ""
    },"Cstm_PF_ADG_URT_Demographics": {
      "school_grade": "family setting","school_grade_code": ""
    },"Cstm_Precert_Medical_Current_Meds": [
      {
        "med_name": "med1","dosage": "10mg","frequency": "daily"
      },{
        "med_name": "med2","dosage": "20mg","frequency": "daily"
      }
    ],"Cstm_PF_ADG_URT_Substance_Use": {
      "dimension1_comment": "dimension 1 - tab1","Textbox1": "text - tab1"
    },"Cstm_PF_ADG_Discharge_Note": {
      "prior_auth_no_comm": "auth no - tab2"
    },"Cstm_PF_ADG_URT_Clinical_Plan": {
      "cca_cs_dhs_details": "details - tab2"
    },"container": {
      "Cstm_PF_Name": {
        "first_name": "same text for textbox - footer","last_name": "second textbox - footer"
      },"Cstm_PF_ADG_URT_Demographics": {
        "new_field": "mapped demo - footer"
      },"grid2": [
        {
          "Cstm_PF_ADG_COMP_Diagnosis": {
            "diagnosis_label": "knee","diagnosis_group_code": "leg"
          }
        },{
          "Cstm_PF_ADG_COMP_Diagnosis": {
            "diagnosis_label": "ankle","diagnosis_group_code": "leg"
          }
        }
      ]
    },"submit": true
  }
};

function getNamesAndValues(data,id) {
  const tablesAndValues = [],res = data;
 
  Object.entries(res).map(([key,value]) => {
    const newKey = key.split('_')[0].toLowerCase();
    
    // console.log(newKey) // -> 'cstm'
    
    if (newKey === id) {
      tablesAndValues.push({
        table: key,values: value
      });
    } else {
      // I can log value and key and see what I want to push 
      // to the tablesAndValues array,but I can't seem to get 
      // how to push the nested items.
      
      // console.log(value);
      // console.log(key);
      
      // getNamesAndValues(value,key)
    }
  });
  
  return tablesAndValues;
}

console.log(getNamesAndValues(response.data,'cstm'));

解决方法

您只需要使用rest运算符在else语句中调用push to tableAndValues并将值和id作为参数传递

const response = {
  "data": {
    "Cstm_PF_ADG_URT_Disposition": {
      "child_welfare_placement_value": ""
    },"Cstm_PF_ADG_URT_Demographics": {
      "school_grade": "family setting","school_grade_code": ""
    },"Cstm_Precert_Medical_Current_Meds": [
      {
        "med_name": "med1","dosage": "10mg","frequency": "daily"
      },{
        "med_name": "med2","dosage": "20mg","frequency": "daily"
      }
    ],"Cstm_PF_ADG_URT_Substance_Use": {
      "dimension1_comment": "dimension 1 - tab1","Textbox1": "text - tab1"
    },"Cstm_PF_ADG_Discharge_Note": {
      "prior_auth_no_comm": "auth no - tab2"
    },"Cstm_PF_ADG_URT_Clinical_Plan": {
      "cca_cs_dhs_details": "details - tab2"
    },"container": {
      "Cstm_PF_Name": {
        "first_name": "same text for textbox - footer","last_name": "second textbox - footer"
      },"Cstm_PF_ADG_URT_Demographics": {
        "new_field": "mapped demo - footer"
      },"grid2": [
        {
          "Cstm_PF_ADG_COMP_Diagnosis": {
            "diagnosis_label": "knee","diagnosis_group_code": "leg"
          }
        },{
          "Cstm_PF_ADG_COMP_Diagnosis": {
            "diagnosis_label": "ankle","diagnosis_group_code": "leg"
          }
        }
      ]
    },"submit": true
  }
};

function getNamesAndValues(data,id) {
  const tablesAndValues = [],res = data;
 
  Object.entries(res).map(([key,value]) => {
    const newKey = key.split('_')[0].toLowerCase();
    
    // console.log(newKey) // -> 'cstm'
    
    if (newKey === id) {
      tablesAndValues.push({
        table: key,values: value
      });
    } else {
      // I can log value and key and see what I want to push 
      // to the tablesAndValues array,but I can't seem to get 
      // how to push the nested items.
      
      // console.log(value);
      // console.log(key);
      
      tablesAndValues.push(...getNamesAndValues(value,id))
    }
  });
  
  return tablesAndValues;
}

console.log(getNamesAndValues(response.data,'cstm'));

或更短的方式

function getNamesAndValues2(data,id) {
    return Object.entries(data).reduce((arr,[key,value]) => {
        arr.push(
            ...(key.split('_')[0].toLowerCase() === id ? [{ table: key,values: value }] : getNamesAndValues(value,id))
        );
        return arr
    },[]);
}
,

要通过一次推送获得结果,可以在递归调用时将结果表传递给函数,但在第一次调用时默认将其传递给空表。由于未使用返回值,因此我也将.map更改为.forEach

const response = {
  "data": {
    "Cstm_PF_ADG_URT_Disposition": {
      "child_welfare_placement_value": ""
    },id,tablesAndValues = []) {
  const res = data;
 
  Object.entries(res).forEach(([key,value]) => {
    const newKey = key.split('_')[0].toLowerCase();
    if (newKey === id) {
      tablesAndValues.push({
        table: key,values: value
      });
    } else {
        getNamesAndValues( value,tablesAndValues);    }
  });
    return tablesAndValues;
}

console.log(getNamesAndValues(response.data,'cstm'));

,

这是工作版本。如果值是数组或对象,则以递归方式调用main函数。每次也会传入计数数组的当前状态。

function getNamesAndValues(data,tablesAndValues = []) {
  const res = data;
 
  Object.entries(res).map(([key,value]) => {
    const newKey = key.split('_')[0].toLowerCase();
    const item = res[key];

    if (newKey === id) {
      tablesAndValues.push({
        table: key,values: value
      });
    }
    
    if(Array.isArray(item)) {
        return item.map(el => getNamesAndValues(el,tablesAndValues));
    }

    if(typeof item === 'object') {
        return getNamesAndValues(item,tablesAndValues);
    }

  })

  return tablesAndValues;
}

console.log(getNamesAndValues(response.data,'cstm'));
,

这是使用生成器的另一种方法-

const keySearch = (t = [],q = "") =>
  filter(t,([ k,_ ]) => String(k).startsWith(q))

const r = 
  Array.from
    ( keySearch(response,"Cstm"),([ table,values ]) =>
        ({ table,values })
    )

console.log(r)
[
  {
    table: 'Cstm_PF_ADG_URT_Disposition',values: { child_welfare_placement_value: '' }
  },{
    table: 'Cstm_PF_ADG_URT_Demographics',values: { school_grade: 'family setting',school_grade_code: '' }
  },{
    table: 'Cstm_Precert_Medical_Current_Meds',values: [ [Object],[Object] ]
  },{
    table: 'Cstm_PF_ADG_URT_Substance_Use',values: {
      dimension1_comment: 'dimension 1 - tab1',Textbox1: 'text - tab1'
    }
  },{
    table: 'Cstm_PF_ADG_Discharge_Note',values: { prior_auth_no_comm: 'auth no - tab2' }
  },{
    table: 'Cstm_PF_ADG_URT_Clinical_Plan',values: { cca_cs_dhs_details: 'details - tab2' }
  },{
    table: 'Cstm_PF_Name',values: {
      first_name: 'same text for textbox - footer',last_name: 'second textbox - footer'
    }
  },values: { new_field: 'mapped demo - footer' }
  },{
    table: 'Cstm_PF_ADG_COMP_Diagnosis',values: { diagnosis_label: 'knee',diagnosis_group_code: 'leg' }
  },values: { diagnosis_label: 'ankle',diagnosis_group_code: 'leg' }
  }
]

以上,keySearch只是filter的专业化-

function* filter (t = [],test = v => v)
{ for (const v of traverse(t)){
    if (test(v))
      yield v
  }
}

traverse的专业化-

function* traverse (t = {})
{ if (Object(t) === t)
    for (const [ k,v ] of Object.entries(t))
      ( yield [ k,v ],yield* traverse(v)
      )
}

展开下面的代码片段,以在浏览器中验证结果-

function* traverse (t = {})
{ if (Object(t) === t)
    for (const [ k,yield* traverse(v)
      )
}

function* filter (t = [],test = v => v)
{ for (const v of traverse(t)){
    if (test(v))
      yield v
  }
}

const keySearch = (t = [],_ ]) => String(k).startsWith(q))

const response =
  {"data":{"Cstm_PF_ADG_URT_Disposition":{"child_welfare_placement_value":""},"Cstm_PF_ADG_URT_Demographics":{"school_grade":"family setting","school_grade_code":""},"Cstm_Precert_Medical_Current_Meds":[{"med_name":"med1","dosage":"10mg","frequency":"daily"},{"med_name":"med2","dosage":"20mg","frequency":"daily"}],"Cstm_PF_ADG_URT_Substance_Use":{"dimension1_comment":"dimension 1 - tab1","Textbox1":"text - tab1"},"Cstm_PF_ADG_Discharge_Note":{"prior_auth_no_comm":"auth no - tab2"},"Cstm_PF_ADG_URT_Clinical_Plan":{"cca_cs_dhs_details":"details - tab2"},"container":{"Cstm_PF_Name":{"first_name":"same text for textbox - footer","last_name":"second textbox - footer"},"Cstm_PF_ADG_URT_Demographics":{"new_field":"mapped demo - footer"},"grid2":[{"Cstm_PF_ADG_COMP_Diagnosis":{"diagnosis_label":"knee","diagnosis_group_code":"leg"}},{"Cstm_PF_ADG_COMP_Diagnosis":{"diagnosis_label":"ankle","diagnosis_group_code":"leg"}}]},"submit":true}}

const result = 
  Array.from
    ( keySearch(response,values })
    )

console.log(result)

,

一个合理的递归答案可能看起来像这样:

const getNamesAndValues = (obj) => 
  Object (obj) === obj
    ? Object .entries (obj)
        .flatMap (([k,v]) => [
          ... (k .toLowerCase () .startsWith ('cstm') ? [{table: k,value: v}] : []),... getNamesAndValues (v)
        ])
    : []

const response = {data: {Cstm_PF_ADG_URT_Disposition: {child_welfare_placement_value: ""},Cstm_PF_ADG_URT_Demographics: {school_grade: "family setting",school_grade_code: ""},Cstm_Precert_Medical_Current_Meds: [{med_name: "med1",dosage: "10mg",frequency: "daily"},{med_name: "med2",dosage: "20mg",frequency: "daily"}],Cstm_PF_ADG_URT_Substance_Use: {dimension1_comment: "dimension 1 - tab1",Textbox1: "text - tab1"},Cstm_PF_ADG_Discharge_Note: {prior_auth_no_comm: "auth no - tab2"},Cstm_PF_ADG_URT_Clinical_Plan: {cca_cs_dhs_details: "details - tab2"},container: {Cstm_PF_Name: {first_name: "same text for textbox - footer",last_name: "second textbox - footer"},Cstm_PF_ADG_URT_Demographics: {new_field: "mapped demo - footer"},grid2: [{Cstm_PF_ADG_COMP_Diagnosis: {diagnosis_label: "knee",diagnosis_group_code: "leg"}},{Cstm_PF_ADG_COMP_Diagnosis: {diagnosis_label: "ankle",diagnosis_group_code: "leg"}}]},submit: true}}

console .log (getNamesAndValues (response))
.as-console-wrapper {max-height: 100% !important; top: 0}

但这不是我想要的那么简单。此代码将搜索的匹配项以及在该搜索中使用的测试与输出的格式混合在一起。这意味着它是一个自定义函数,与我想要的相比,它既理解起来更复杂,并且可重用性更低。

我宁愿使用一些可重用的功能,将此功能的三个功能分开。因此,尽管以下内容涉及更多的代码行,但我认为这更有意义:

const findAllDeep = (pred) => (obj) => 
  Object (obj) === obj
    ? Object .entries (obj)
        .flatMap (([k,v]) => [
          ... (pred (k,v) ? [[k,v]] : []),... findAllDeep (pred) (v)
        ])
    : []

const makeSimpleObject = (name1,name2) => ([k,v]) => 
 ({[name1]: k,[name2]: v})

const makeSimpleObjects = (name1,name2) => (xs) => 
  xs .map (makeSimpleObject (name1,name2))

const cstmTest = k => 
  k .toLowerCase () .startsWith ('cstm')

const getNamesAndValues = (obj) => 
  makeSimpleObjects ('table','values') (findAllDeep (cstmTest) (obj))

const response = {data: {Cstm_PF_ADG_URT_Disposition: {child_welfare_placement_value: ""},submit: true}}

console .log (findAllDeep (cstmTest) (response))
.as-console-wrapper {max-height: 100% !important; top: 0}

这些都是不同程度的可重用性的辅助功能:

  • makeSimpleObject 接受两个键名,例如'foo''bar',并返回一个包含两个元素的数组的函数,例如{ {1}}并返回与之匹配的对象,例如[10,20]

  • {foo: 10,bar: 20} 对包含两个元素的数组makeSimpleObjects做同样的事情。

  • makeSimpleObjects('foo','bar')([[8,6],[7,5],[30,9]]) //=> [{foo: 8,bar: 6},{foo: 7,bar: 5},{foo: 30,bar: 9}] 是一个简单的谓词,用于测试键是否以cstmTest(不区分大小写)开头。

  • "cstm" 带有一个谓词,并返回一个函数,该函数接收一个对象并返回一个包含两个元素的数组,并保留所有匹配谓词。 (该谓词既提供了键又提供了值;在当前情况下,我们只需要键,但是对于函数而言,采用这两个键似乎都是明智的。

我们的主要功能 findAllDeep 使用getNamesAndValues查找匹配值,然后使用findAllDeep (cstmTest)将结果转换为最终格式。

请注意,makeSimpleObjects ('table','values')findAllDeepmakeSimpleObject都是在别处可能有用的功能。此处的自定义仅在makeSimpleObjectscstmTest的简短定义中。我认为这是一次胜利。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-