Matt Yoü
Matt Yoü

Reputation: 15

How to handle repeating values in JQuery

I'm trying to dynamically render values I am pulling from SQL that looks like this:

enter image description here

into something that looks like this:

enter image description here

I already have HTML and CSS placed and I am approaching this using $.each but I cant seem to populate the inside of the view tree:

enter image description here

EDIT:

here is my script:

AjaxGet('GetUserAppFeatures', { "uid": userid }, false, true)
        .success(function (result) {

            $.each(result.model, function (val) {

                var li = $('<li></li>');

                li.append('<span class="caret">' + result.model[val].AppName + '</span> <input type="checkbox" id="chkApp' + result.model[val].AppId + '">');

                var ul = $('<ul class="nested"></ul>');
                $.each(result.model[val], function (index) {

                    ul.append('<li>' + result.model[val].FeatureName[index] + '</li> <input type="checkbox" id="chkApp' + result.model[val].FeatureId[index] + '">');

                    li.append(ul);
                });


                treeview.append(li);

            });

        });

Upvotes: 0

Views: 119

Answers (2)

Kalpesh Dabhi
Kalpesh Dabhi

Reputation: 802

For this type of data you need to group by.

var yourData = [
{Name : "Forms", value : "Request"},
{Name : "Forms", value : "Report"},
{Name : "Forms", value : "Password"},
{Name : "Energy", value : "Report"},
{Name : "Energy", value : "CUstomer Multiplier"},
{Name : "Energy", value : "Product Feedback"},
];
Renderdata();
function Renderdata(){
  var data = groupBy(yourData,"Name");
  var html = '';
  for(var i= 0 ; i < data.length; i++){
    html += "<div>"+data[i][0].Name+" </div>"+"<ul>";
   for(var j= 0 ; j < data[i].length; j++){
    html += "<li>"+data[i][j].value+"</li>";
  } 
  html += "</ul>";
  }
  $('#div').html(html);
}

function groupBy(collection, property) {
    var i = 0, val, index,
        values = [], result = [];
    for (; i < collection.length; i++) {
        val = collection[i][property];
        index = values.indexOf(val);
        if (index > -1)
            result[index].push(collection[i]);
        else {
            values.push(val);
            result.push([collection[i]]);
        }
    }
    return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div"></div>

Upvotes: 1

UberRose
UberRose

Reputation: 86

Perhaps you need an intermediate step where you construct an array modelling the second image you have there. Something like:

// Do this before $.each()
var sql_data = {
    Forms: [],
    Energy: []
};


// Inside of $.each() do something like this:
sql_data[col_1].push(col_2);

Where "col_1" and "col_2" are respectively the first and second columns in your data. Then you can use that "sql_data" object to create the HTML that you need.

Upvotes: 0

Related Questions