簡體   English   中英

我如何深入遍歷類似JSON的數據結構以返回總計

[英]How do I deeply traverse a JSON-like data structure to return a total of something

對於這個模糊的問題,我表示歉意。 希望我的示例可以使我的問題更加清楚...因此,我有一個像這樣的分層數據結構:

var Company = {
    root: {
        title: 'CEO',
        employees: [{
            title: 'Vice President',
            employees: [{
                title: 'Sales Lead'
            }, {
                title: 'Marketing Lead'
            }]
        }]
    }
};

我的問題是如何找出根對象中的雇員總數? 直觀地看到,公司中有3名員工。 我正在與遞歸合作以嘗試解決此問題,但是我似乎無法使其正常工作或為此工作。 我感謝任何幫助,技巧或建議:)

您可以將.reduce與可以遞歸調用的命名函數一起使用。 基本情況是對象沒有雇員。

const totalEmployees = Company.root.employees.reduce(countEmployees, 0);

function countEmployees(prev, next) {
    // count *this* employee
    let sum = prev + 1;
    if (next.employees && next.employees.length) {
      // count any nested employees
      sum += next.employees.reduce(countEmployees, 0);
    }
    return sum;
}

您可以使用遞歸函數遍歷嵌套的對象結構。

這是您的操作方式。

function countEmployee(root){

    if(!root.employees){
        return 0;
    }

    var numOfEmployee = root.employees.length;; 

    var count = 0;

    for(var i=0; i<numOfEmployee; i++){
        count = count + countEmployee(root.employees[i]);
    }

    numOfEmployee = numOfEmployee + count;

    return numOfEmployee;
}

countEmployee(Company.root); //return 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM