2016-09-30 50 views
0

は、検索する方法を、この2次元配列の要素をunderscore.jsで見つける方法は?続き

function(subItem) { 
       scope.currentItem = _.find(scope.subItems, function(sm){ 
        return subItem.name === sm.name; 
       }); 
} 

今では多くの問題がある私たちは、

$scope.items = [ 
{ 
    name: "Item1", 
    subItems: [ 
     {name: "SubItem1"}, 
     {name: "SubItem2"} 
    ] 
}, 
{ 
    name: "Item2", 
    subItems: [ 
     {name: "SubItem3"}, 
     {name: "SubItem4"}, 
     {name: "SubItem5"} 
    ] 
}, 
{ 
    name: "Item3", 
    subItems: [ 
     {name: "SubItem6", 
     subSubItems: [ 
      {name: "SubItem6-1"}, 
      {name: "SubItem6-2"} 
     ]       
     } 
    ] 
} 
]; 

はサブアイテムを見つけるには(コンパイルされないことがあり、実際のコードから簡体字)擬似コードの一種であるsubSubItem名前で?

答えて

0

私はちょうどあなたがサブアイテム

items = [{ 
 
    name: "Item1", 
 
    subItems: [{ 
 
    name: "SubItem1" 
 
    }, { 
 
    name: "SubItem2" 
 
    }] 
 
}, { 
 
    name: "Item2", 
 
    subItems: [{ 
 
    name: "SubItem3" 
 
    }, { 
 
    name: "SubItem4" 
 
    }, { 
 
    name: "SubItem5" 
 
    }] 
 
}, { 
 
    name: "Item3", 
 
    subItems: [{ 
 
    name: "SubItem6", 
 
    subSubItems: [{ 
 
     name: "SubItem6-1" 
 
    }, { 
 
     name: "SubItem6-2" 
 
    }] 
 
    }] 
 
}]; 
 

 
var findSubItem = function(subItemName, subSubItemName, subItems) { 
 
    var subItem = _.find(subItems, function(subItm) { 
 
    return subItm.name === subItemName; 
 
    }); 
 
    var subSubItem = _.find(subItem.subSubItems, function(itm) { 
 
    return itm.name === subSubItemName; 
 
    }); 
 
    return subSubItem 
 
} 
 

 
var sampleSubItems = [{ 
 
    name: "SubItem6", 
 
    subSubItems: [{ 
 
    name: "SubItem6-1" 
 
    }, { 
 
    name: "SubItem6-2" 
 
    }] 
 
}] 
 

 
setTimeout(function() { 
 
    var res = findSubItem("SubItem6", "SubItem6-1", sampleSubItems); 
 
    $("#result").html(JSON.stringify(res)); 
 
}, 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"></div>

検索方法としてsubSubItemを検索したいです
関連する問題