how to push data in array if data in another array?

Total Post:46

 1324  View(s)
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) {
                id: value[],
                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) {
            id: value[],
            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

        cnic: value[tDataValues.cnic]

But like this it can not be a common function.


  1. Post:28

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


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


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

    for (var key in tDataValues) {
            var obj = {};
            obj[key] = value[tDataValues[key]];

      Modified On Apr-06-2018 01:57:06 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.