避免循环内循环

我想知道是否有任何方法可以避免循环内循环,例如:

let underscore = require('underscore'); _.each(obj, (val, key) => { _.each(key, (val, key) => { _.each(key, (val, key) => { // Finally i have access to the value that i need }); }); }); 

我正在处理一个复杂的MAP对象,其中有地图和数组。 显然我不能取代循环..但我想知道如果我可以改变我的代码,使其更清楚。

谢谢。

       

网上收集的解决方案 "避免循环内循环"

是的,你可以用比这里更干净的方式来分解代码,以避免嵌套循环。 比方说你有这样的结构:

 // lets invent some hash of people, where each person // has an array of friends which are also objects var people = { david: { friends: [{name:'mary'}, {name:'bob'}, {name:'joe'}] }, mary: { friends: [{name:'bob'}, {name:'joe'}] } }; function eatFriendBecauseImAZombie(myName, friendName) { console.log(myName + ' just ate ' + friendName + '!!'); } // (inner loop 2) how to parse a friend function parseFriend(myName, friend) { eatFriendBecauseImAZombie(myName, friend.name); } // (inner loop 1) how to parse a person function parsePerson(name, info) { _.each(info.friends, (val) => parseFriend(name, val)); } // (outer loop) loop over people _.each(people, (val, key) => parsePerson(key, val)); 

输出是:

 david just ate mary!! david just ate bob!! david just ate joe!! mary just ate bob!! mary just ate joe!!