【发布时间】: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