1

I am having two for loops. One nested in another. I want to iterate on a single Object and change a property in it with another value, something like this:

for(i=0;i<items.length;<i++){
 obj.changeThisAttribute = "abc";
  for(j=0;j<items.anotherobj.length;j++){
   items.anotherobj.changeThisAttribute = "dyz";
  }
}
return items;

Is there any better way of doing this? I have read about Async.map and think that it will be a good solution however there is no good example of the same. Please suggest a running example or any alternative way of achieving this.

V31
  • 7,626
  • 3
  • 26
  • 44

1 Answers1

1

You're not performing anything asynchronous here so there is no point in async.map.

Unless this is very CPU intensive (looks fine! profile, how many objects do you have?) , your code looks fine.

It's readable, straightforward and simple, no need to look for alternative ways.

(I'm assuming your inner loop goes through items[i].anotherobj and not items.anotherobj though)

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • You mean to say my code will take all the items in parallel just like Async.map and do it at the same performance level? – V31 May 08 '13 at 03:31
  • you can add a process.nextTick call inside the async.map function to defer execution until later. However like Benjamin said there doesn't seem to be any reason to go through the callback system since the sample code you posted will run quite quickly. The callbacks will just add more overhead – Noah May 08 '13 at 14:42
  • 1
    @Noah It's probably better to use setImmidiate and not nextTick to allow events to pass (see http://stackoverflow.com/questions/15349733/setimmediate-vs-nexttick ). Splitting on ticks is a known technique though :) – Benjamin Gruenbaum May 08 '13 at 15:42
  • good call, setImmediate is better here. For others reading this note that it is spelled setImmediate – Noah May 08 '13 at 15:47
  • asyn.forEachSeries is best what I am using now for this. – V31 Feb 11 '14 at 08:46
  • @V31 you might want to look into promises :) – Benjamin Gruenbaum Feb 11 '14 at 11:01