JavaScript recursive search in JSON object

后端 未结 6 482
野趣味
野趣味 2020-11-30 04:21

I am trying to return a specific node in a JSON object structure which looks like this

{
    \"id\":\"0\",
    \"children\":[
        {
            \"id\":\"         


        
6条回答
  •  时光取名叫无心
    2020-11-30 04:43

    I use the following

    var searchObject = function (object, matchCallback, currentPath, result, searched) {
        currentPath = currentPath || '';
        result = result || [];
        searched = searched || [];
        if (searched.indexOf(object) !== -1 && object === Object(object)) {
            return;
        }
        searched.push(object);
        if (matchCallback(object)) {
            result.push({path: currentPath, value: object});
        }
        try {
            if (object === Object(object)) {
                for (var property in object) {
                    if (property.indexOf("$") !== 0) {
                        //if (Object.prototype.hasOwnProperty.call(object, property)) {
                            searchObject(object[property], matchCallback, currentPath + "." + property, result, searched);
                        //}
                    }
                }
            }
        }
        catch (e) {
            console.log(object);
            throw e;
        }
        return result;
    }
    

    Then you can write

    searchObject(rootNode, function (value) { return value != null && value != undefined && value.id == '10'; });
    

    Now this works on circular references and you can match on any field or combination of fields you like by changing the matchCallback function.

提交回复
热议问题