我试图在lodash库的帮助下从我的多维数组中找到匹配的对象。我正在使用_.chain
和flatten的组合来更深层次。
不知道我应该使用什么方法。任何人都可以查看并帮助我获得预期的结果吗?
var team = _.chain(data).flatten("divisionTeams").find({"id": 3222}).value();
答案 0 :(得分:2)
您应首先使用map()
返回divisionTeams
,然后展平并查找。
var data = [{"divisionName":"5th Grade - Green","divisionTeams":[{"id":3222,"name":"Columbia Ravens 5th","coach":"John Miller"},{"id":4299,"name":"D1 Spartans","coach":"Jacob Silverman"},{"id":3220,"name":"HC Elite OMalley 5th","coach":"Eddie OMalley"},{"id":3277,"name":"MD 3D 5th","coach":"Marty Libinski"},{"id":3275,"name":"Severn Elite Gold","coach":"Darryl Adams"},{"id":3224,"name":"Team Dedication 5th","coach":"Don Carpenter"}]},{"divisionName":"5th Grade - White","divisionTeams":[{"id":3225,"name":"CBSA Hoyas 5th Grade","coach":"Terrance Taylor"},{"id":3276,"name":"HC Elite 4th Tookes","coach":"Anthony Tookes"},{"id":3221,"name":"HC Elite Knisley 5th","coach":"Jordan Knisley"},{"id":3226,"name":"Randelstown Runnin Rebels 5th","coach":"Eric Levi"},{"id":3223,"name":"Up n Coming Clippers 5th","coach":"Brian Jackson"}]}]
var team = _.chain(data)
.map(e => e.divisionTeams)
.flatten()
.find({ "id": 3222})
.value();
console.log(JSON.stringify(team));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>