查找具有匹配ID

时间:2019-01-18 13:02:27

标签: javascript arrays multidimensional-array

感谢您的检查, 我有一个动态数组,其中将包含多个项目/对象。 如果提供的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]

2 个答案:

答案 0 :(得分:0)

递归执行

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;
}

答案 1 :(得分:0)

您可以在了解一些按键的情况下采用完整的动态方法。

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; }