更好的实践:消除嵌套循环?

时间:2015-09-21 17:42:53

标签: javascript loops underscore.js

我正在迭代这样的一些对象(使用Underscore.js):

      _.each(obj.Things, function(thing) {
        _.each(thing.SubThings, function(subThing) {
          _.each(subThing.SubSubThing, function(subSubThing) {
            things.push(subSubThing);
          });
        });
      });

从架构上讲,我不喜欢这看起来如何。有没有更简洁的方法来完成这样的任务?

3 个答案:

答案 0 :(得分:1)

使代码更具可读性的一种方法是展开嵌套调用并使用常规函数调用。

_.each(obj.Things, processThing);

function processThing(thing) {
    _.each(thing.SubThings, processSubThing);
}

function processSubThing(subThing) {
    _.each(subThing.SubSubThing, processSubSubThing);
}

function processSubSubThin(subSubThing) {
    things.push(subSubThing);
}

如果您使用ES6 / ES2015,则可以使用箭头功能

let processThing = thing => _.each(thing.SubThings, processSubThing);

let processSubThing = subThing => _.each(subThing.SubSubThing, processSubSubThing);

let processSubSubThin = subSubThing => things.push(subSubThing);

_.each(obj.Things, processThing);

答案 1 :(得分:0)

所有对象都是数组吗?

然后,这有意义吗?

var things = _.flatten(_.map(obj.Things, function(thing) {
    return _.pluck(thing.SubThings, "SubSubThings");
}));

如果你不想创造新事物。

things.push(_.map(obj.Things, function(thing) {
  return _.pluck(thing.SubThings, "SubSubThings");
}));
things = _.flatten(things);

答案 2 :(得分:0)

使用Array.prototype.mapArray.prototype.reduce,存在一个充分表达的解决方案:

var things = obj.Things.map(function (thing) {
    return thing.SubThings;
}).reduce(function (things, subthing) {
    return things.concat(subthing.SubSubThings);
}, []);