1
\$\begingroup\$

I'm pretty sure there's a way to make this "3 times" duplicated code into only one. Any idea how to do this?

if (typeof sync.create!='undefined') {
 for (var i = 0; i <sync.create.length; i++) {
 sync.create[i].modified.id_partenaire=false;
 }; 
} 
if (typeof sync.update!='undefined') {
 for (var i = 0; i <sync.update.length; i++) {
 sync.update[i].modified.id_partenaire=false;
 }; 
} 
if (typeof sync.destroy!='undefined') {
 for (var i = 0; i <sync.destroy.length; i++) {
 sync.destroy[i].modified.id_partenaire=false;
 }; 
} 
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 21, 2012 at 10:52
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

If this should be executed on all properties of sync in general, i'd go with a for..in loop.

for(var prop in sync){
 if(sync.hasOwnProperty(prop) && typeof sync[prop] !== 'undefined'){
 var i=0, l = sync[prop].length;
 for (i; i < l; i+=1) {
 sync[prop][i].modified.id_partenaire=false;
 };
 }
}

Otherwise, if there are more properties and this should only be applied to these 3, Esailija's answer works better.

answered Jun 21, 2012 at 11:05
\$\endgroup\$
1
  • \$\begingroup\$ I didn't want on all properties, but thank you very much for you suggestion, this may help for other object / properties manipulations in the future. \$\endgroup\$ Commented Jun 22, 2012 at 9:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.