我需要一个数组来包含我的JavaScript对象的每个键(例如[“中枢神经系统”,“不典型畸胎样横纹肌肉瘤”,“脉络丛瘤”,“脉络丛乳头状瘤”,...)
以下是它的摘录:
var tumor_types = {
"CNS" : {
"Atypical teratoid rhabdoid tumor" : {
"Category" : "Direct referral",
"Educational-page" : "/assets/educational-page/atypical-teratoid-rhabdoid-tumor.docx",
},
"Choroid plexus tumor" : {
"Choroid plexus papilloma" : {
"Category" : "Universal criteria",
"Educational-page" : "/assets/educational-page/choroid-plexus-papilloma.docx",
},
"Choroid plexus carcinoma" : {
"Category" : "Direct referral",
"Educational-page" : "/assets/educational-page/choroid-plexus-carcinoma.docx",
}
},
"Embryonal tumor of the CNS - NOS" : {
"Category" : {
"Algorithm" : 1,
"Educational-page" : "/assets/educational-page/embryonal-tumor-CNS-NOS.docx"
}
},
[...]因此,在键"Category“之前,我需要将肿瘤名称推入一个数组中。这是到目前为止我的递归函数(我第一次做递归):
function get_all_tumors_name(data) {
var result = [];
$.each(data, function(key, value) {
result.push(key);
console.log($.type(value));
if(key != 'Category' && key != 'Educational-page') {
var names = get_all_tumors_name(value);
result = result.concat(names);
}
});
return result
}当我运行我之前的代码时,我有一个数组,但在它里面有很多"Category“和”Educational page“,我不想要它们。这就是我添加key != 'Category' && key != 'Educational-page'检查的原因。我的情况还能更好吗?或者我应该简单地从数组中删除每个“类别”和“教育页面”?在我看来,这并不是最理想的。
任何帮助或提示都将不胜感激!
发布于 2018-07-31 04:09:14
尝试使用递归方法,该方法在找到具有Category键的对象时终止分支:
var tumor_types={"CNS":{"Atypical teratoid rhabdoid tumor":{"Category":"Direct referral","Educational-page":"/assets/educational-page/atypical-teratoid-rhabdoid-tumor.docx",},"Choroid plexus tumor":{"Choroid plexus papilloma":{"Category":"Universal criteria","Educational-page":"/assets/educational-page/choroid-plexus-papilloma.docx",},"Choroid plexus carcinoma":{"Category":"Direct referral","Educational-page":"/assets/educational-page/choroid-plexus-carcinoma.docx",}},"Embryonal tumor of the CNS - NOS":{"Category":{"Algorithm":1,"Educational-page":"/assets/educational-page/embryonal-tumor-CNS-NOS.docx"}}}}
const getKeys = (obj, keys=[]) => {
const theseKeys = Object.keys(obj);
if (theseKeys.includes('Category')) return;
keys.push(...theseKeys);
const theseValues = Object.values(obj);
theseValues.forEach(child => getKeys(child, keys));
return keys;
}
console.log(getKeys(tumor_types));
https://stackoverflow.com/questions/51601402
复制相似问题