【问题标题】:Recursively loop through objects of object递归循环遍历对象的对象
【发布时间】:2020-12-06 03:01:58
【问题描述】:

我正在尝试编写一个递归函数来遍历对象并根据 ID 返回项目。我可以让它的第一部分工作,但我很难尝试以递归方式获得这个功能并且可以使用一组新的眼睛。代码如下。当您运行 sn-p 时,您会得到一个包含 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'));

【问题讨论】:

  • 在你的 else 子句中,你可能想要连接递归调用的结果,比如return [...tablesAndValues, ...getNamesAndValues(value, key)]
  • @rayhatfield 感谢您的回复,雷。我会试试看。
  • 更新了我的评论以传播递归调用的结果。
  • 我尝试了更新的代码,但没有骰子。那里仍然只有6个项目。不过我喜欢这种方法,所以我会看看我能做什么。

标签: javascript object recursion


【解决方案1】:

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

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, 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, id, tablesAndValues);    }
  });
    return tablesAndValues;
}

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

【讨论】:

  • 就是这样。也感谢这个答案。在else 中使用第三个参数很有趣,我需要阅读那里发生的事情。再次非常感谢。
【解决方案2】:

您只需要在 else 语句中使用 rest 运算符调用 push 到 tablesAndValues 并将值和 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
    }, []);
}

【讨论】:

  • 这很酷。我不知道我可以传播getNamesAndValues() 函数。理想情况下,我试图只使用一个.push(),但也许这是不可能的。不管怎样,谢谢你的回答。
  • 为了好玩,我用三元和 reduce 做了一些改变,你可以在 getNamesAndValues2 看到
【解决方案3】:

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

function getNamesAndValues(data, id, 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, id, tablesAndValues));
    }

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

  })

  return tablesAndValues;
}

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

【讨论】:

    【解决方案4】:

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

    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'
        }
      },
      {
        table: 'Cstm_PF_ADG_URT_Demographics',
        values: { new_field: 'mapped demo - footer' }
      },
      {
        table: 'Cstm_PF_ADG_COMP_Diagnosis',
        values: { diagnosis_label: 'knee', diagnosis_group_code: 'leg' }
      },
      {
        table: 'Cstm_PF_ADG_COMP_Diagnosis',
        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)
          )
    }
    

    展开下面的sn-p,在浏览器中验证结果-

    function* traverse (t = {})
    { if (Object(t) === t)
        for (const [ k, v ] of Object.entries(t))
          ( yield [ k, v ]
          , yield* traverse(v)
          )
    }
    
    function* filter (t = [], test = v => v)
    { for (const v of traverse(t)){
        if (test(v))
          yield v
      }
    }
    
    const keySearch = (t = [], q = "") =>
      filter(t, ([ k, _ ]) => 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, "Cstm")
        , ([ table, values ]) =>
            ({ table, values })
        )
    
    console.log(result)

    【讨论】:

      【解决方案5】:

      一个相当优雅的递归答案可能如下所示:

      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: ""}, 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 (findAllDeep (cstmTest) (response))
      .as-console-wrapper {max-height: 100% !important; top: 0}

      这些都是可重用程度不同的辅助函数:

      • makeSimpleObject 接受两个键名,比如'foo' 和'bar',并返回一个函数,该函数接受一个二元素数组,比如[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')将结果转换为最终格式。

      请注意,findAllDeep、makeSimpleObject 和 makeSimpleObjects 都是可能在其他地方有用的函数。此处的自定义仅在cstmTest 和getNamesAndValues 的简短定义中。我会认为这是一场胜利。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        相关资源
        最近更新 更多