尝试获取嵌套JSON对象的对象键

时间:2018-08-18 23:10:56

标签: javascript json object

我需要获取以下JSON对象中所有键名的列表:

var myJSON = [
    {
        "Employees_Name": "Bill Sanders",
        "Work_plan_during_my_absence": "Work from home",
        "Assigned To-Manager Approval": [
            "mymanager@gmail.com"
        ],
        "AbsenceVacation_Summary": [
            {
                "Computed_Leave_Days": 2,
                "From_Date": "2018-08-20",
                "To_Date": "2018-08-21",
                "Id": "Shccbcc230_a30f_11e8_9afa_25436d674c51"
            }
        ],
        "Leave_Type": "Work from Home",
        "Reporting_Manager": "My Manager",
        "Total_Days": 2,
    }
]

当我使用Object.keys方法时,它仅检索顶级键名称:

var keys_arr = Object.keys(myJSON[0]);
console.log(keys_arr);

结果是一个数组:

"[ 'Employees_Name', 'Work_plan_during_my_absence', 'Assigned To-Manager
Approval', 'AbsenceVacation_Summary', 'Leave_Type', 'Reporting_Manager',
'Total_Days']"

缺少的键名是“ AbsenceVacation_Summary”中的键名。

我认为我需要做的是遍历返回的名称数组,看看值是对象还是数组...但是我不知道该怎么做。请告知。

1 个答案:

答案 0 :(得分:0)

您是对的,您需要递归遍历对象结构以发现嵌套的对象并收集其键:

function collectKeys(inputObject, outputKeys) {
    if (Array.isArray(inputObject)) {
        for(let i = 0; i < inputObject.length; i++) {
            collectKeys(inputObject[i], outputKeys);
        }
    } else if (typeof inputObject === 'object') {
        Object.keys(inputObject).forEach(function(key) {
            outputKeys.push(key);
            collectKeys(outputKeys[key], outputKeys);
        });
    }
}
var collectedKeys = [];
collectKeys(myJSON, collectedKeys);

Working fiddle here

结果将显示在控制台中

参考