HOW TO PUSH DATA IN ARRAY IF DATA IN ANOTHER ARRAY?

sandy taylor

Total Post:46

Points:324
Posted by  sandy taylor
 872  View(s)
Ratings:
Rate this:

data in this array

var tDataValues = {

        id: "Userid",

        text: "Name",

        username: "Username",

        cnic: 'CNIC'

    }

i am sending this variable to the function

commonSelect2Templating(selector, url, tDataValues, minInputLength, placeholder);

Note: I'm using Jquery Select2 (Sharing if it can help my question to understand.)

Then in that function in results Section i am trying to assign values

results: function(data, page) {

        var newData = [];

        var length = data.length + 1;

        for(var i = 0; i<=length; i++){

 

        }

        $.each(data, function (index,value) {

            newData.push({

                id: value[tDataValues.id],

                text: value[tDataValues.text]

            });

        });

        return { results: newData };

    }

This is the data coming from the Server:

[{ " Userid ""21""Name""Rohit Kesharwani""Username""Rohit""CNIC""16141-6321136-1" }, { " Userid ""22""Name""Kamlakar Singh""Username""Kamlakar""CNIC""17301-5856870-1" }, { " Userid ""23""Name""Pawan Shukla""Username""Pawan""CNIC""15165-6156685-6" }]

Coming to the The Problem: Right now all the magic is happening here.

$.each(data, function (index, value) {

        newData.push({

            id: value[tDataValues.id],

            text: value[tDataValues.text]

        });

    });

Its Telling the code which is id and which is text, and it is working perfectly fine.

Now the Problem here is function i am trying to make is Common Function for the select2, and if i have more values from db, like now i am getting from database how to make a loop and set those values one by one to its proper context. e-g tDataValues holds the fieldName cnic and server is sending the fieldName CNIC so how to make a loop that if cnic exist in both then it should simply assign,

i can do that manually

newData.push({

        cnic: value[tDataValues.cnic]

    });

But like this it can not be a common function.

 

  1. Kamlakar Singh

    Post:28

    Points:196
    Re: how to push data in array if data in another array?

    Try:

    for (var key in tDataValues) {

            newData.push({ key: value[tDataValues[key]] });

        }

    Update:

    then create an object first and push it to the array:

    for (var key in tDataValues) {

            var obj = {};

            obj[key] = value[tDataValues[key]];

            newData.push(obj);

        }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!