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.
Mark M
31-Oct-2014Update:
then create an object first and push it to the array: