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.

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

6 Comments

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?
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 It's probably better to use setImmidiate and not nextTick to allow events to pass (see stackoverflow.com/questions/15349733/setimmediate-vs-nexttick ). Splitting on ticks is a known technique though :)
good call, setImmediate is better here. For others reading this note that it is spelled setImmediate
asyn.forEachSeries is best what I am using now for this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.