簡體   English   中英

查找具有匹配ID的動態多維數組/ json的索引

[英]Find index of a dynamic multidimensional array/json with matches id

感謝您的檢查,我有一個動態數組,其中將包含多個項目/對象。 我想要此數組的索引號,如果提供的ID與其中包含的ID匹配的話

但是因為它是動態生成的array / json,所以它在子項中可以具有任意數量的多維數組,依此類推。

因此,有什么方法可以找到具有匹配ID的索引號。

var data = [
            {

                id:1,
                child:[
                    {
                        id: 2,
                        child: [
                            {
                                id: 3,
                                child: []
                            },
                            {
                                id:4,
                                child:[
                                    {
                                        id:44,
                                        child:[
                                            {
                                                id:55,
                                                child:[]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]

                    },
                    {
                        id:5,
                        child:[
                            {
                                id:6,
                                child:[]
                            }
                        ]
                    }
                ]
            }
        ]

假設我要獲取id等於4的數組的索引。我需要開發一個邏輯/函數,該邏輯/函數將返回-> data[0]['child'][0]['child'][1]

遞歸執行

function findId(obj, id, currentPath = "") {
    // Go through every object in the array
    let i = 0;
    for (let child of obj) {
        // If id matches, return
        if (child.id == id) return currentPath + `[${i}]`;
        // Else go through the children, if we find anything there, return it
        let next = findId(child.child, id, currentPath + `[${i}]['child']`);
        if (next) return next;
        i++;
    }

    // We didn't find anything
    return null;
}

您可以在了解一些密鑰的情況下采用完整的動態方法。

 function findPath(object, id) { var path; if (!object || typeof object !== 'object') return; if (object.id === id) return []; Object.entries(object).some(([k, o]) => { var temp; if (temp = findPath(o, id, path = [])) { path = [k, ...temp]; return true; } }); return path; } var data = [{ id: 1, child: [{ id: 2, child: [{ id: 3, child: [] }, { id: 4, child: [{ id: 44, child: [{ id: 55, child: [] }] }] }] }, { id: 5, child: [{ id: 6, child: [] }] }] }]; console.log(findPath(data, 44)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

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

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