解析多级javascript对象并仅检索键

时间:2018-07-30 19:57:12

标签: javascript

我需要一个数组,其中包含我的JavaScript对象的每个键(例如[“ CNS”,“非典型类畸形横纹肌瘤”,“脉络丛肿瘤”,“脉络丛乳头状瘤”,[...])

这是它的摘录:

    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"
            }
        },
        [...]

因此,在键“类别”之前,我需要将肿瘤名称放入数组中。到目前为止,这是我的递归函数(我第一次进行递归):

    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

}

当我运行之前的代码时,我有一个数组,但在其中却有很多我不想要的“类别”和“教育页”。这就是为什么我添加了key != 'Category' && key != 'Educational-page'检查的原因。我的病情好吗?还是我应该简单地从数组中删除每个“类别”和“教育页”?在我看来,这不是很理想。

任何帮助或提示将不胜感激!

1 个答案:

答案 0 :(得分:0)

尝试使用递归方法,该方法在找到具有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));