Simplify my function (loop, array)?

I have a function that repeats several times, and I believe that it is possible to simplify and send variables from an array.

var i = masterdata.timing.split(','); var index = 0; for (index = 0; index < i.length; ++index) { $("#timing_" + i[index].trim()).prop('checked', true); } var i = masterdata.concern.split(','); var index = 0; for (index = 0; index < i.length; ++index) { $("#concern_" + i[index].trim()).prop('checked', true); } var i = masterdata.steps.split(','); var index = 0; for (index = 0; index < i.length; ++index) { $("#steps_" + i[index].trim()).prop('checked', true); } 

Perhaps just change the categories to a variable and send directories from an array?

 var chkgroup = [ 'timing, concern, steps' ] 
+6
source share
3 answers

Your idea should work fine:

 var i; var index = 0; var j = 0; var chkgroup = ['timing', 'concern', 'steps']; var currentGroup; for (j = 0; j < chkgroup.length; ++j) { currentGroup = chkgroup[j]; i = masterdata[currentGroup].split(','); for (index = 0; index < i.length; ++index) { $("#" + currentGroup + "_" + i[index].trim()) .prop('checked', true); } } 

If the chkgroup array really matches the keys object in masterdata , you can use the external for..in loop for..in :

 var i; var index = 0; var currentGroup; for (currentGroup in masterdata) { i = masterdata[currentGroup].split(','); for (index = 0; index < i.length; ++index) { $("#" + currentGroup + "_" + i[index].trim()) .prop('checked', true); } } 

Note that there is no order for for...in , so if you need to ensure that you iterate over the properties of an object in a specific order, it might be better to use a predefined array.

You can also get an idea of $.map :

 var values = $.map(masterdata, function (i, currentGroup) { return $.map(i.split(','), function (val) { return $('#' + currentGroup + '_' + val.trim()); }); }); $(values).prop('checked', true); 
+4
source
 var chkgroup = [ 'timing', 'concern', 'steps' ]; setProps( chkgroup, masterdata ); function setProps( c, m ) { $.each(c, function(i, group) { var i = m[group]split(','); var index = 0; for (index = 0; index < i.length; ++index) { $("#" + group + "_" + i[index].trim()).prop('checked', true); } }); } 
0
source

Actually your code is still a bit noisy and unreadable, i.e. the developer must spend at least a few minutes analyzing it to see if the logic is correct. Using loDash or Underscore, your code can be simplified and turned into this:

  var selector = _.chain(masterdata) //pick only needed items .pick(masterdata, 'timing', 'concern', 'steps') .map(function (item, key) { //split and transform the string into selector, eg #timing_1 var ids = item.split(','); var mapped = _.map(ids, function (id) { return "#" + key + "_" + id.trim(); }); return mapped.join(); }) .value() .join(); $(selector).prop('checked', true); 

And a working sample on jsfiddle

0
source

Source: https://habr.com/ru/post/976832/


All Articles