简体   繁体   中英

How to handle repeating values in JQuery

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

在此处输入图像描述

into something that looks like this:

在此处输入图像描述

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:

在此处输入图像描述

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);

            });

        });

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM