Filtering from a file to show information I want to get my code cleanner and more efficient. This code gets variables form a PHP file and filters it to show the selected user name, all available usergroups on a list box and the groups he is currently into in another.
&lt;script&gt;
    
    function saveGroup(type,id){
      $('#useridgr').attr('placeholder', '').val('');
      $(&quot;#usernamegr&quot;).attr('placeholder', 'Nome').val('');
      $('#list_box').html('');
      $('#list_box_ini').html('');
    
      if (type == 1){
    
    
      } else {
        loadatagroup(id);
      }
    
    }
    var loadatagroup = (uid) =&gt; {
    
      $.ajax({
        type: 'GET',
        url: 'usergrupo/' + uid,
        data: {'_token': $(&quot;input[name='_token']&quot;).val()},
        success: function(data){
    
    
          console.log(&quot;success&quot;);
    
          var o = data[0];
    
          $('#useridgr').attr('placeholder',o.id).val(o.id);
          $(&quot;#usernamegr&quot;).attr('placeholder',o.name).val(o.name);
    
          console.log('areaa');
    
          var size = Object.size(data);
    
    
    
    
          console.log(size);
    
    
          for (var i=0; i&lt;size; i++){
            var o = data[i];
            $(&quot;#list_box&quot;).append(&quot;&lt;option value='&quot;+o.idgrupo+&quot;'&gt;&quot;+o.nome+&quot;&lt;/option&gt;&quot;);
          }
    
     
        }
    
      })
    
    }
    
    Object.size = function(obj) {
      var size = 0, key;
      for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
      }
      return size;
    };
    
    &lt;/script&gt;
Since you are using jquery, you can use its built in each function to loop through the json results, which will eliminate the need for the size function.
i = index, v = values
$.each(data,function(i,v){
   $(&quot;#list_box&quot;).append(&quot;&lt;option value='&quot;+v.idgrupo+&quot;'&gt;&quot;+v.nome+&quot;&lt;/option&gt;&quot;);
})