Reputation: 403
I have a set of values for a DropDownList. My requirement is before setting on the DropDown, values need to be stored in a javascript variable using loop in the below format:
var categories = [{
"value": 1,
"text": "Keyboard"
},{
"value": 2,
"text": "Mouse"
},{
"value": 3,
"text": "Monitor"
}];
I created a sample like below:
dataType: "json",
data: { categoryId: CategoryHdId },
success: function (data) {
var categories = [];
for (i = 0; i < data.length; i++) {
case = {
"value": data[i].ddlSubCategoryId,
"text": data[i].SubCategoryName
}
categories.append(case);
}
}
But this gives a
Syntax Error
and
Uncaught TypeError: categories.append is not a function
Can anyone help how to set them inside the loop.
Upvotes: 1
Views: 91
Reputation: 9808
case
is a reserved word in javascript so you can't use it as a variable name, use some other variable name. Also use push()
to add values to an array.
dataType: "json",
data: { categoryId: CategoryHdId },
success: function (data) {
var categories = [];
for (i = 0; i < data.length; i++) {
// case = { reserved word case will throw syntax error
someVar = { //declare as var if you don't want it to be global
"value": data[i].ddlSubCategoryId,
"text": data[i].SubCategoryName
}
categories.push(someVar);
}
}
Upvotes: 4
Reputation: 10264
dataType: "json",
data: { categoryId: CategoryHdId },
success: function (data) {
var categories = [];
for (i = 0; i < data.length; i++) {
let temp = {
"value": data[i].ddlSubCategoryId,
"text": data[i].SubCategoryName
}
categories.push(temp);
}
}
Upvotes: 0
Reputation: 2675
Try with this
var categories = [];
for (i = 0; i < data.length; i++) {
categories.push({ "value": data[i].ddlSubCategoryId, "text": data[i].SubCategoryName })
}
Upvotes: 2