A Coder
A Coder

Reputation: 3046

Loop inside a $.each() statement

I'm having a result inside which there are 5 items. Now under certain conditions i have to push those items in an array and bind it in jqgrid as columns and rows. So i have to loop into the result(something like that). How can i do?

//Code:

var colname = [];
    var colHeader = [];

    $.ajax({
        url: '@(Url.Action("LoadColumns", "Home"))',
        datatype: 'json',
        mtype: 'GET',
        success: OnComplete,
        error: OnFail
    });
    function OnComplete(result) {
        var i = 0;
        $.each(result, function () {
            console.log(result.rows[i]);
           var currentRow = result.rows[i];
           colHeader.push(currentRow.Name);
          // alert(currentRow.Name);
           switch (currentRow.Datatype) {

                case 'int':
                    colname.push({ name: currentRow.Name, index: currentRow.Name, width: 200, align: 'left', sortable: true, editable: false, sorttype: 'int' });
                    break;
                case 'String':
                    colname.push({ name: currentRow.Name, index: currentRow.Name, width: 200, align: 'left', sortable: true, editable: true });
                    break;
                case 'DateTime':
                    colname.push({
                        name: currentRow.Name, index: currentRow.Name, width: 200, align: 'left', sortable: true, editable: true, sorttype: 'date',
                        formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y'
                    });
                    break;
                case 'dropdown':
                    if (currentRow.ValueList != null && currentRow.ValueList != '') {
                        var ValueListArray = currentRow.ValueList.split(" ");
                        var valueListItems = '';
                        $.each(ValueListArray, function (index, values) {
                            valueListItems = valueListItems + values + ":" + values + ";";
                        });
                    }
                    colname.push({
                        name: currentRow.Name, index: currentRow.Name, width: 200, edittype: "select", formatter: 'select',
                        editoptions: { value: valueListItems.slice(0, -1) }, stype: 'select'
                                , searchoptions: { value: ':All;' + valueListItems.slice(0, -1) }, align: 'left', sortable: true, editable: true
                    });
                    break;

            }

            i++;
        });
}

when i tried i'm getting only one value getting printed for 11 times.

Not sure where i'm wrong? Kindly help.

Upvotes: 0

Views: 1464

Answers (2)

A Coder
A Coder

Reputation: 3046

Got the answer, done something like this.

//Code:

 var colname = [];
    var colHeader = [];

    $.ajax({
        url: '@(Url.Action("LoadColumns", "Home"))',
        datatype: 'json',
        mtype: 'GET',
        success: OnComplete,
        error: OnFail
    });
    function OnComplete(result) {

        $.each(result.rows, function (inx,val) {

           colHeader.push(this.Name);

           switch (this.Datatype) {

                case 'int':
                    colname.push({ name: this.Name, index: this.Name, width: 200, align: 'left', sortable: true, editable: false, sorttype: 'int' });
                    break;
                case 'String':
                    colname.push({ name: this.Name, index: this.Name, width: 200, align: 'left', sortable: true, editable: true });
                    break;
                case 'DateTime':
                    colname.push({
                        name: this.Name, index: this.Name, width: 200, align: 'left', sortable: true, editable: true, sorttype: 'date',
                        formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y'
                    });
                    break;
                case 'dropdown':
                    if (this.ValueList != null && this.ValueList != '') {
                        var ValueListArray = this.ValueList.split(" ");
                        var valueListItems = '';
                        $.each(ValueListArray, function (index, values) {
                            valueListItems = valueListItems + values + ":" + values + ";";
                        });
                    }
                    colname.push({
                        name: this.Name, index: this.Name, width: 200, edittype: "select", formatter: 'select',
                        editoptions: { value: valueListItems.slice(0, -1) }, stype: 'select'
                                , searchoptions: { value: ':All;' + valueListItems.slice(0, -1) }, align: 'left', sortable: true, editable: true
                    });
                    break;

            }


        });
}

Upvotes: 0

Oleg
Oleg

Reputation: 221997

It seems that you are new in JavaScript language. The most people start with another language and have to use JavaScript language later. The problem is that JavaScript language is quite different as C++/C# or Java which is probably your current favorite language. I strictly recommend you to change the style of your JavaScript code. Don't use the same style which you use in your other favorite language.

First of all you should follow the name conversion which are standard in JavaScript language. You can see already from the text of you question that OnComplete, OnFail or ValueListArray have another color as i variable for example. The reason: names of variables having the first capital letter are used as constructors of objects only. So one use

var d = new Date();

for example instead of var d = Date();.

In the same way you should not always trying to use foreach construct which you probably like in C#. The current version of JavaScript don't have the construct. So the usage of

var i, rows = result.rows, n = rows.length, item;
for (i = 0; i < n; i++) {
    item = rows[i];
    // now you can work with item
}

is much more quickly as the usage of $.each. You can see that I saved the values of rows property (result.rows) in a variable and I saved rows.length in the next variable instead of usage rows.length directly in for loop. It improves the performance too because don't optimize the code. It can be that the size of rows array will be changes or even that length property will be overwritten by your custom implementation inside of for body. So JavaScript don't make any code optimization and saving unchanged property value in a variable will improve the performance.

Even the usage of colHeader variable defined in outer scope of OnComplete function works slowly as working with local variable colHeader. Probably you can do all the work inside of OnComplete (after the loop $.each)? The current code makes OnComplete closure. It works in other way like you good knows in C#. So I recommend you to invest your time in studding JavaScript language. The argument after which I decide to do this for me was the fact that JavaScript don't have block level variables and use function level variables instead. If one don't understand that then one can write and read the code which will be interpreted by JavaScript in absolutely another way as you think. See the answer for more details.

One more remark about the code

colname.push({ name: currentRow.Name, index: currentRow.Name, width: 200,
    align: 'left', sortable: true, editable: false, sorttype: 'int' });

and other close lines. jqGrid don't have any data type. On the other side one can use column templates (see the answer) which can make your code shorter and more readable.

Upvotes: 2

Related Questions