Underscore.js:深层嵌套对象中的匹配字符串

时间:2016-01-15 23:06:00

标签: javascript json underscore.js

我需要找出这个深层嵌套数组中的哪个对象包含字符串Toys & Games(嵌套中最深的对象)。

我正在尝试用以下方法选择正确的对象:

var arr = _.filter(data, function(obj) {
    return _.some(obj.Ancestors, {'Name': "Toys & Games"});
});

传递给data的{​​{1}}是:

.filter

1 个答案:

答案 0 :(得分:0)

我最终在没有Underscore的情况下执行此操作,而是使用异步while循环:

function traverseNodes(nodeList,findMe,callbackMM){

    var nodeArr = []; //collect all browse nodes

    async.eachSeries(nodeList, function(item, callbackZ) {

        var currentNode = item;
        var childNodeId = currentNode.BrowseNodeId[0]; //get first ID in nest tree

        async.whilst(
            function () { 
                if (currentNode.Name && currentNode.Name[0] == findMe){ //we found the string, stop traversing
                    nodeArr.push(childNodeId);
                    return false;
                }else if (currentNode.Ancestors){ //didn't find string, keep traversing
                    currentNode = currentNode.Ancestors[0].BrowseNode[0];
                    return true;
                }
                else {
                    return false;
                }
            },
            function (callback) {
                callback();                                                                
            },
            function (err) {
                if (err){
                    console.log('WHILST error in search.js ',err);
                }
                callbackZ();
            }
        );     

    }, function done(){
        if (nodeArr.length > 0){                                                    
            callbackMM(nodeArr.toString()); 
        }
        else {
            console.log('error: no browseNodes found')
        }                                          
    });                                  

}